Why does Java not support multiple inheritance of classes, and what problem does that decision solve?
Because a class can only have one parent, Java avoids the ambiguity that comes with two.
Here is the problem. Suppose class A and class B both declare a field called size, and class C extends both of them. Now the line c.size has no single answer, because the compiler does not know whether you meant the one from A or the one from B. The same thing happens with a method that both parents define differently.
Java could have solved this by making you write it out, in the way that you write super.field to reach a parent's field when a child hides it. The language designers decided that the confusion was not worth it, and that giving every class exactly one parent was a fair price.
The rule is only about classes. A class can implement any number of interfaces, because an interface describes what a class can do rather than what data it holds, so two interfaces rarely collide in the first place.
public class Main {
public static void main(String[] args) {
// One superclass and several interfaces: no conflict.
Dog dog = new Dog();
System.out.println(dog.describe());
System.out.println(dog.bark());
System.out.println(dog.fetch());
}
}
class Animal {
String describe() {
return "an animal";
}
}
interface Pet {
String bark();
}
interface Fetchable {
String fetch();
}
class Dog extends Animal implements Pet, Fetchable {
public String bark() {
return "woof";
}
public String fetch() {
return "fetched the ball";
}
}
The next question in this topic looks at the shape of this problem that has its own name.