What is inheritance, and what does a subclass actually get from its parent?
Inheritance is a way of saying that one class is a special kind of another class. The child class gets the fields and the methods of the parent, and it can add more or change some of them.
public class Main {
public static void main(String[] args) {
Square s = new Square(3);
System.out.println(s.area()); // 9
}
}
And here is the parent and the child.
public class Shape {
protected final String name;
public Shape(String name) {
this.name = name;
}
public double area() {
return 0;
}
public String describe() {
return name + " with area " + area();
}
}
public class Square extends Shape {
private final double side;
public Square(double side) {
super("square");
this.side = side;
}
@Override
public double area() {
return side * side;
}
}
So what does a subclass actually get from its parent? Four things.
what it gets what that means
------------------------ --------------------------------------------
the public methods they can be called on the child
the protected methods they can be called from the child
the package-private only if the child is in the same package
methods
the fields the fields come along, with the access
level that they had
And the private fields come along too, but the child cannot touch them directly. The child inherits the data but it has to go through the parent's methods to get at it. That is an important detail, because it is the reason that a parent with private state still works properly.
And the constructors are not inherited. The child has to run one of the parent's constructors, and if you do not write a super call then Java puts in the one that takes no arguments.
what is inherited what is not
-------------------------- ------------------------------------
the fields, with their the constructors
access levels
the methods, with their the static methods, though they can
access levels be called through the child
the nested classes the private members, for direct use
And there is one more thing worth knowing about. The child gets a copy of the parent's fields, not a share of them. So if a parent field is an object, then the parent and the child point at the same object. That is a common source of bugs, because the child can then change an object that the parent also uses.
And there is a detail about the fields that is worth knowing about too. A field that is private in the parent is still there in the child, and a field with the same name in the child hides the parent's one. So the child has two fields with that name, and the parent's methods use the parent's one and the child's methods use the child's one.
So the rule to remember is this. The child gets the parent's fields and methods, but it does not get the constructors.
The next two questions in this topic are about substitutability and about spotting a bad hierarchy.