Thursday, 12 January 2017

Why multiple inheritance is not supported in java?

First of all try to understand what is diamond problem?

Consider the below diagram which shows multiple inheritance as Class D extends both Class B & C. Now lets say we have a method in class A and Class B & C overrides that method in their own way. Now problem comes here – 

Assume, method hello() is overridden in Class B and C.

Class D is extending both B & C, so now if Class D wants to use the same method i.e. hello(), which method would be called ? the overridden method hello() of B or or C ?.  Because of this ambiguity java doesn’t support multiple inheritance.

Also, multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

However, you can achieve multiple inheritance in Java using interfaces. Assume in above diagram B and C is interface not a class, then class D can implement the method hello() and this will be common implementation in class D.

interface B
{
   public void hello();
}
interface C
{
   public void hello();
}
class D implements B, C
{
   public void hello()
   {
       System.out.println(" Multiple inheritance example using interfaces");
   }
}

No comments:

Post a Comment