What types of inheritance does Java support, and which ones are impossible?
Java supports three kinds of inheritance between classes, and two kinds that it does not support at all.
The three that it supports are single, multilevel and hierarchical inheritance.
Single inheritance means that one class extends one other class. A class named Dog extends a class named Animal, and that is the whole relationship.
Multilevel inheritance means a chain. A class named Puppy extends Dog, and Dog extends Animal. The puppy is an animal, but it gets there through the dog.
Hierarchical inheritance means that several classes extend the same parent. Both Dog and Cat extend Animal, and neither of them knows about the other.
The two that Java does not support are multiple inheritance, where a class extends two classes at once, and hybrid inheritance, which is multiple inheritance combined with multilevel or hierarchical inheritance. A class can only ever extend one class.
The important thing to notice is that a class can implement several interfaces. The rule is about classes and not about interfaces, and the reason is the subject of the last question in this topic.
public class Main {
public static void main(String[] args) {
// Hierarchical: Dog and Cat both extend Animal.
Animal first = new Dog();
Animal second = new Cat();
System.out.println(first.describe());
System.out.println(second.describe());
// Multilevel: Puppy extends Dog, and Dog extends Animal.
Puppy puppy = new Puppy();
System.out.println(puppy.describe());
// The type of the reference decides what you can call.
System.out.println("is an animal : " + (first instanceof Animal));
}
}
class Animal {
String describe() {
return "an animal";
}
}
class Dog extends Animal {
@Override
String describe() {
return "a dog";
}
}
class Cat extends Animal {
@Override
String describe() {
return "a cat";
}
}
class Puppy extends Dog {
@Override
String describe() {
return "a puppy";
}
}
The next question in this topic looks at how you write each kind, and at what you are allowed to override.