Home / Programs / Multiple inheritance is not supported in java
Programming Example

Multiple inheritance is not supported in java

👁 1,210 Views
💻 Practical Program
📘 Step by Step Learning
Learn why multiple inheritance is not supported in Java with our explanation. Understand how the language addresses the diamond problem and explore the difference between multiple and multilevel inheritance.

Information & Algorithm

Multiple inheritance is not supported in Java because it can lead to the diamond problem, which occurs when a class inherits from two classes, both of which have a common parent class. In such cases, the ambiguity arises as to which parent class method should be inherited by the child class.

To avoid this problem, Java uses interfaces, which provide a way to achieve multiple inheritance by allowing a class to implement multiple interfaces. This way, the ambiguity problem is avoided as interfaces only contain method signatures and the implementation of those methods is done by the implementing class.

Program Code

 class A{
void msg(){
	System.out.println("Hello");
	}
}

class B{
void msg(){
	System.out.println("Welcome");
	}
}

class C extends A,B{//suppose if it were

 Public Static void main(String args[]){
   C obj=new C();
   obj.msg();//Now which msg() method would be invoked?
 }
}

Output

compile time error

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.