Why multiple inheritance is not supported in JAVA?

In this post, we will see why multiple inheritance is not supported in java and how we can achieve it. Many programmers know the multiple inheritances is not supported in java but only some of them know what is the reason behind and how we can achieve the multiple inheritances in java?
Here is the table content of the article will we will cover this topic.
1. What is Multiple inheritance in java?
2. What Problem occurs in multiple inheritance in Java?
3. What is the diamond problem?

4. How to achieve multiple inheritances?

What is Multiple inheritance in java

In Multiple inheritance, there is only one class derived class that inherits the features from more than one base class. Java doesn’t allow more than one base class.

multiple inheritance in java

In this example, class A and class B are base classes that inherited by class C(Derived class).

What Problem occurs in multiple inheritance in Java?

As you can see in the example the derived class (class c) inherits all features of base classes (class A and class B). The problem occurs if both base classes (class A and class B) have the same methods with the same signature. The compiler can’t determine which class method to be called. It creates ambiguity for the compiler.

1. The multiple inheritance also creates problems in constructor chaining.
2. Multiple inheritance is the cause of the diamond problem.

What is the diamond problem?

Let’s say We have four classes A, B, C, and D.
A is the Base class that extends by B and C. The B and C are also extended by class D. Suppose class A has a method show() that overridden by Class B and Class C.
When the programmer tries to call show() method in Class D then the compiler will get confused about which method would be called? That’s the main reason why Java doesn’t support multiple inheritance.

class BaseClass1 
{ 
    void showData() 
    { 
        System.out.println("This is the base class 1"); 
    } 
} 
  
class BaseClass2
{ 
	 void showData() 
	 { 
	    System.out.println("This is the base class 2"); 
	 } 
} 
  
// Error : Test is inheriting from multiple 
// classes 
class DerivedClass extends BaseClass1, BaseClass2 
{
   public static void main(String args[]) 
   { 
	   DerivedClass t = new DerivedClass(); 
       t. showData(); 
   } 
}

Output: Compilation error

Java supported the multiple inheritance by using the interfaces. We will discuss it in later chapters. You can visit here for Multiple inheritance

Leave a Comment