Advanced Java Programming - Old Questions

10. Why multiple inheritance is not allowed in Java using classes? Give an example.(5)

5 marks | Asked in 2077

Multiple inheritance is where we inherit the properties and behavior of multiple classes to a single class. In java, multiple inheritance is not supported because of ambiguity problem. We can take the below example where we have two classes Class1 and Class2 which have same method display(). If multiple inheritance is possible than Test class can inherit data members and methods of both Class1 and Class2 classes. Now, Test class have two display() methods inherited from Class1 and Class2. Problem occurs in method call, when display() method will be called with Test class object which method will be called, will it be of Class1 or Class2. This is ambiguity problem because of which multiple inheritance is not allowed in java.

Example:

class Class1{

      public void display(){

            System.out.println("Class 1 Display Method");

      }

}

class Class2{

      public void display(){

            System.out.println("Class 2 Display");

      }

}

public class Test extends Class1, Class2{

      public static void main(String args[]){

            Test obj = new Test();

            //Ambiguity problem in method call which class display() method will be called.

            obj.display();

      }

}