top of page

Why multiple Inheritance of classes are not allowed in java?

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.


ree

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:


  1. 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.


Class over Interface:


If a class inherits a method from both a superclass and an interface, the method in the superclass takes precedence.


ree

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.


ree

3. Explicit Override: If there is still ambiguity, the class must explicitly override the conflicting method and provide its own implementation


ree

Happy Coding 🚀

Recent Posts

See All

Comments


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page