What kinds of inheritance relationships can you build in Java, and how do they differ?
Java lets a class extend at most one class, but a class may implement any number of interfaces. From that rule you get the familiar shapes. Single inheritance is one class extending one other, the simplest case. Multilevel inheritance is a chain, where a class extends a class that extends another class. Hierarchical inheritance is one parent with several children. Hybrid inheritance combines multilevel and hierarchical, and in Java it always involves interfaces, because class inheritance cannot branch.
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
System.out.println(dog.describe());
System.out.println(dog.speak());
Puppy puppy = new Puppy();
System.out.println(puppy.speak());
}
}
class Animal {
String describe() { return "an animal"; }
String speak() { return "..."; }
}
class Dog extends Animal {
String speak() { return "woof"; }
}
class Puppy extends Dog {
String speak() { return "yip"; }
}The example shows both single and multilevel relationships. The dog extends Animal, which is single inheritance. The puppy extends Dog, which extends Animal, which is multilevel, and the puppy inherits describe from Animal two levels up. The output also shows overriding at each level: the dog prints woof and the puppy prints yip, because the most specific override wins at run time.
That last point is the one to explain carefully, because it is easy to get wrong. The puppy does not have three separate copies of speak. It has one method, and the runtime picks the implementation based on the object's actual class. If a caller holds an Animal reference to a puppy and calls speak, it still prints yip.
One more thing worth adding: Java does not have multiple inheritance of classes, and that restriction is deliberate. A class can still end up implementing behaviour from several sources, through interfaces and default methods, but the state of a class comes from exactly one parent. That removes the ambiguity in how inherited fields are combined.