Multiple inheritance in java

Let’s learn multiple inheritance in java.

Multiple inheritance in java

Multiple inheritance is a feature where child class extends more than one parent classes. Let’s see 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 we have two parent classes, class X and class Y. Now child class Z extends both class X and Y.

Here immediately we get compile time error:

Z.java:9: error: '{' expected
class Z extends X, Y

Why? What is the reason?

In the above example assume there is method print() in class X and class Y. Now through inheritance concept whatever parent class has is by default available to child class.

If I call obj.print() from main method compiler cannot determine which parent class method to execute. This type of problem is called as ambiguity problem. This is the reason java do not support multiple inheritance.

The concept of multiple inheritance is achieved through interfaces. Let’s see an example.

interface M
{
   
}
interface N
{
   
}
interface A extends M, N
{
   
}

So java provides support for multiple inheritance in interfaces but not in classes. Because in interfaces there is only method declaration no implementation.

An interface can extend more than one or any number of interfaces simultaneously.


Also read – interface in java