Why does Java not allow a class to extend more than one class?
To avoid the diamond problem, where two parents define the same method and the child cannot tell which one to inherit. Java allows multiple interfaces instead, and since Java 8 a conflicting default method must be resolved explicitly.
Explain it simply
Suppose both your father and your mother tell you what to cook for dinner, and give different answers. Which one do you follow? With two parent classes that both define start(), the child has the same confusion. Java's designers removed the situation by allowing only one parent class.
Example
interface Phone { default String ring() { return "phone ring"; } }
interface Alarm { default String ring() { return "alarm ring"; } }
class SmartWatch implements Phone, Alarm {
@Override
public String ring() {
// must choose, or compilation fails
return Phone.super.ring() + " + " + Alarm.super.ring();
}
}
// new SmartWatch().ring() returns: phone ring + alarm ringWhat to say in the interview
"A class can extend only one class, which prevents the diamond problem and keeps the object's state layout simple, because multiple parents would mean multiple copies of fields. A class can implement many interfaces because interfaces historically had no state. With default methods, if two interfaces give the same default, the class must override the method and may call a specific one using InterfaceName.super.method()."
Common mistakes
- Saying Java has no multiple inheritance at all. It has multiple inheritance of type through interfaces.