Multiple inheritance in java

Let’s learn multiple inheritance in java.

Multiple inheritance in java

Multiple inheritance is one of the object oriented feature where a class or a sub class can inherit features from more than one parent class or super class.

But here problem occurs when methods with same signature exist in both parent class and child class. Because when you execute java program with methods with same signature in both parent class and child class compiler cannot determine which class method to be called. This is the reason java do not support multiple inheritance.

Why java do not support multiple inheritance?

Let’s see why java does not support multiple inheritance in java with an example.

class X
{
   void print()
   {
   }
}
class Y
{
   void print()
   {
   }
}
class Z extends X, Y
{
   public static void main(String[] args)
   {
      Z obj = new Z();
      obj.print()
   }
}


In the above example I have class X and class Y which has method print(). Now third class Z extends both class X and Y.

Now in main() method I’m creating object ‘obj’ of class Z and I’m calling method print(). Here compiler gets confused to call method print() of class X or class Y. This type of error is called as ambiguity error.

This is the main reason multiple inheritance is not supported. The concept of multiple inheritance is achieved through interfaces. Let’s see an example.

interface M
{
   public void helloWorld();
}
interface N
{
   public void helloWorld();
}
// implementing interfaces
public class MultipleInheritanceExample implements M, N
{
   public void helloWorld()
   {
      System.out.println("helloWorld() method");
   }
   public static void main(String[] args)
   {
      MultipleInheritanceExample obj = new MultipleInheritanceExample();
      obj.helloWorld();
   }
}


Output:

helloWorld() method

In the above example class MultipleInheritanceExample implements two interfaces: interface M and interface N.

In java a class can implement more than one interface. By implementing interface in multiple inheritance there is no ambiguity even though we have same method helloWorld() in interface M and interface N. Because in java, by default interface is abstract.


Hybrid inheritance

Hybrid inheritance in general is a combination of any two or more types of inheritance in java. Like multiple inheritance, hybrid inheritance is achieved through interfaces.


Also read – interface in java