Does Java support multiple inheritance?

Java directly does  not support multiple inheritance , but by interface it supports the same.

To understand why java does not support multiple inheritance  first we need to understand the Diamond problem

Diamond problem says

Suppose we have Parent class Color it has a method cal displayColor().

Now it has two children  Yellow and Blue by invoking displayColor(). they return yellow and blue respectively.

Let assume java supports multiple inheritance
So if I create a child say Green which inherits Yellow as well as Blue then which displayColor() color it inherits? It creates an ambiguous  situation so for this reason java does not support multiple inheritance directly but we can solve this problem by the interface. An interface is a contract only methods are declared in  interface no definition so if Green implements yellow and blue ,
Green class easily override displayColor() , and define the same, there will be no problem as only concrete implementation only in Green class.

Example:
public class Color
{
public void displayColor()
{
System.out.println("white");
}
}


public class Yellow extends Color
{
public void displayColor()
{
System.out.println("yellow");
}

}


public class Blue extends Color
{
public void displayColor()
{
System.out.println("blue");
}
}




interface color
{
  void displayColor();
}

interface yellow extends color
{
  void displayColor();
}

interface blue extends color
{
  void displayColor();
}


Class Green implements blue,yellow
{
  public void displayColor()
{
System.out.println("Green")
}

}







Post a Comment