Why does Java not support multiple inheritance of classes?
If a class could extend two classes with the same method, Java would not know which one to use. This is the diamond problem. So a class can extend only one class.
But a class can implement many interfaces. Since interfaces can have default methods now, a clash must be solved by the class:
interface A { default String hi() { return "A"; } }
interface B { default String hi() { return "B"; } }
class C implements A, B {
public String hi() {
return A.super.hi() + B.super.hi(); // you choose
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new C().hi());
}
}
Output
AB
See Java Interfaces.
Learn more about the similar topics:
| Tutorials |
|---|
| Java Classes and Objects |
| Java Constructors |
| Java static and this Keywords |
| Java Encapsulation and Access Modifiers |
| Java Inheritance |
| Java Polymorphism |
| Java Abstract Classes |
| Exercises & Assignments |
|---|
| Build a BankAccount class |
| Calculate areas with inheritance and polymorphism |
| Use a sealed interface and pattern matching |