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 one child class or sub class can inherit features from more than one parent class or super class.

Why java do not support multiple inheritance?

Let’s see multiple inheritance in java with 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