Why multiple Inheritance of classes are not allowed in java?
- Manbodh ratre
- Aug 7, 2024
- 2 min read
meaning a class cannot inherit from more than one superclass. This design decision was made to avoid the complexity and problems associated with multiple inheritance, primarily the Diamond Problem.
Consider the following example in a hypothetical language that allows multiple inheritance:
A
/ \
B C
\ /
D
Class A has a method foo().
Classes B and C inherit from A and possibly override foo().
Class D inherits from both B and C.
In this scenario, if D calls foo(), it is ambiguous whether D should inherit foo() from B or from C. This ambiguity is known as the Diamond Problem.
Avoiding the Diamond Problem
To avoid these complications, Java allows multiple inheritance of interfaces but not of classes. This design choice simplifies the language and avoids the complexities associated with multiple inheritance.
Solution: Interfaces and Multiple Inheritance
In Java, a class can implement multiple interfaces. This provides a form of multiple inheritance without the associated problems of inheriting from multiple classes.
In this example, C can implement both A and B interfaces without any ambiguity, because interfaces do not contain implementation details
But Problem in default method
Default Methods in Interfaces
Since Java 8, interfaces can have default methods (methods with implementation). Java handles the potential conflicts of default methods with a clear and straightforward resolution strategy:
Class over Interface: If a class inherits a method from both a superclass and an interface, the method in the superclass takes precedence.
Most Specific Interface: If a class inherits a method from multiple interfaces, the method from the most specific interface (the one further down the inheritance chain) takes precedence.
Explicit Override: If there is still ambiguity, the class must explicitly override the conflicting method and provide its own implementation.
Class over Interface:
If a class inherits a method from both a superclass and an interface, the method in the superclass takes precedence.
2. Most Specific Interface:
If a class inherits a method from multiple interfaces, the method from the most specific interface (the one further down the inheritance chain) takes precedence.
3. Explicit Override: If there is still ambiguity, the class must explicitly override the conflicting method and provide its own implementation
Happy Coding 🚀
Comments