Why Multiple Inheritance Is Not Supported In Java?

 In Java, multiple inheritance is not supported due to ambiguity. Before deep dive into the actual topic let's understand multiple inheritance, why it's not supported by Java classes, and how Java achieves multiple inheritance through the interface concept.

What is multiple inheritance?

Java is a popular Object Oriented Programming language and multiple inheritance is one of the OOPS concepts. A class that derives or inherits the properties from more than one class is known as multiple inheritance. In a program, a class derives the methods and data variables of more than one class. This helps to reuse the methods and data variables without coding the same logic in different classes.

Why Multiple Inheritance is not supported?

In a Java class, identical methods(similar name and signature) are not allowed. When a sub-class inherits two or more superclasses there is a possibility that identical methods can be present in the superclasses, this causes ambiguity and the Java compiler can't decide which class method to call or which class method has priority so Java doesn't support multiple inheritance.

For example, consider both class A and class B has an add() method that adds and returns the sum of two number. If class C extends both A and B then there is an ambiguity because the same add() method will inherited twice by class C. Java compile cannot decide which class add() to load when sub-class C calls the add() method. Let's see one more type of ambiguity

Diamond Problem 

The diamond problem can arise in class hierarchies involving multiple inheritance. It is also known as the diamond inheritance problem or deadly diamond of death. Let's see an example, consider a class X that has the add() method, and class Y and class Z derive the properties(add() method) of class X . Now if class D derives the properties of  Y and Z  causes ambiguity this is known as diamond problem.

Multiple Inheritance Support By Interface.

Java interface is similar to a class but it contains fully abstract methods or only declared methods and then the class will implement the interface and provide detailed instructions about the behavior of each interface method. This interface feature helps Java to achieve multiple inheritance, a class can inherit as many interfaces as it wants without ambiguity because the method implementation is done by class only.

For example, consider a class Mobile that has implemented Android and IOS interfaces. Both interfaces have similar abstract methods like call(), switchOn(), alarm().. etc. and now the Mobile class provides implementation to call(), switchOn(), and alarm method without any ambiguity.

Post a Comment

Previous Post Next Post
B