Diamond problem in multiple inheritance


Java is object oriented programming language.
Java support various type of inheritance such as:
- Single inheritance - Multilevel inheritance - Hierarchical inheritance - Hybrid inheritance (via interface) However it does not support multiple inheritance using classes to avoid ambiguity and complexity.
Multiple Inheritance :
When a class inheriting from multiple classes is called multiple inheritance. For example - class C inheriting from class B and class A. Since class C is inheriting from multiple classes C has property of both class.
class A { void test1() {} } class B { void test2() {} } class C extends A, B { test1(); test2(); }
In the above case, class C is trying to inherit from both A and B, which can cause a conflict if both have methods with the same signature. While using multiple inheritance some ambiguity can arises, this ambiguity called diamond problem.
Diamond Problem: It is a very classic Java problem, lets understand this by an example there is two classes A and B and there is one common method “Test()” present in both class A and B. Now, when class C do multiple inheritance of class A and B, there is an ambiguity that from which class that common method is inherited in class C.
class A { void test() {} } class B { void test() {} } class C extends A, B { // Not allowed in Java ,Ambiguity: Which test() should be inherited? }
This is called the diamond problem and this is primarily the reason why java does not support multiple inheritance.
Solution - Use Interfaces :
Java solves the multiple inheritance problem by allowing classes to implement multiple interfaces instead of extending multiple classes. Interfaces provide method declarations (and optionally default implementations), and ambiguity is handled explicitly by the programmer.
Subscribe to my newsletter
Read articles from Harshit Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
