Multiple Inheritance With Diamond Problem In Java

Multiple Inheritance in Java

Multiple Inheritance not supported in java but Multiple Inheritance is a feature of object oriented concept. A class can inherit properties of more than one parent class. The problem occurs when there exist methods with same signature in both the super classes and subclass. When child class calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority.
 

Let's take an example, suppose we have two parent class A and B. Both have a test method. Now we created a child Class C. Which is extends the both parents classes. When child class calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority.

Why Java doesn’t support Multiple Inheritance?


Consider the below Java code. It shows error.

 

// First Parent class

class ParentA{

    void fundo(){

        System.out.println("ParentA");

    }
}

// Second Parent Class

class ParentB{

    void fundo(){

        System.out.println("ParentB");

    }
}

// Error : Test is inheriting from multiple

// classes

class Test extends ParentA, ParentB{

   public static void main(String args[]){

       Test t = new Test();

       t.fundo();

   }
}

 

The Diamond Problem:

          GrandParent
           /     \
          /       \
      Parent1      Parent2
          \       /
           \     /
            Test

 

// A Grand parent class in diamond

class GrandParent{
    
void fun(){

        System.out.println("Grandparent");

    }
}

// First Parent class

class Parent1 extends GrandParent{

    void fun(){

        System.out.println("Parent1");

    }
}

// Second Parent Class

class Parent2 extends GrandParent{

    void fun(){

        System.out.println("Parent2");

    }
}

// Error : Test is inheriting from multiple

// classes

class Test extends Parent1, Parent2{

   public static void main(String args[]){

       Test t = new Test();

       t.fun();
   }
}

On calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Beta’s fun() method.

 

 

Related Articles

post a comment