What kinds of inheritance relationships can you build in Java, and how do they differ?
There are three shapes of inheritance relationship, and Java allows two of them for classes. The third one, multiple inheritance, Java does not allow for classes at all.
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
System.out.println(dog.describe());
}
}
And here is the parent and the child for each kind.
// Single inheritance. One parent.
public class Animal {
protected final String name;
public Animal(String name) {
this.name = name;
}
public String describe() {
return "I am " + name;
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public String describe() {
return super.describe() + " and I bark";
}
}
So the three kinds are these.
the kind what it looks like does Java allow it
------------------------ ------------------------------- ----------------
single inheritance one class extends one class yes
multilevel inheritance a chain of three or more yes
multiple inheritance a class extends two classes no
hierarchical inheritance one parent, many children yes
And multilevel inheritance is just single inheritance used twice. So a Dog extends Animal, and a Puppy extends Dog, and the Puppy gets everything from both of them in the chain.
public class Puppy extends Dog {
public Puppy(String name) {
super(name);
}
public String describe() {
return super.describe() + " and I am small";
}
}
And hierarchical inheritance is one parent with several children. So Animal has a Dog and a Cat, and both of them are Animals. That is the most common shape and there is nothing special about it.
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
public String describe() {
return super.describe() + " and I purr";
}
}
And Java does allow a class to implement several interfaces. That is not the same as multiple inheritance of classes, and the reason it is safe is that interfaces do not carry state.
public class Dog extends Animal implements Pet, Trackable {
// ...
}
And there is one detail worth knowing about with multilevel inheritance, and it is the one that bites. If the parent and the child both override the same method, then the call to super from the child goes to the parent's version, and not to the grandparent's. So a chain of three classes can hide a method in the middle and the grandparent's version never runs.
the chain who the super call reaches
------------------- ---------------------------------------
Dog then Puppy the Dog version, not the Animal one
So the rule to remember is this. Java gives you one parent class, any number of interfaces, and any depth of chain you want.
The last question in this topic names the kinds and says which ones Java allows.