Why Java does not support Multiple Inheritance?

Why Java does not support Multiple Inheritance?

Java does not support Multiple Inheritance: Java designer, Mr.James Gosling, committed to keep Java very simple to practice even for novices; infact, it is one of goals and features of Java language. Towards this goal, he avoided multiple inheritance, operator overloading, pointers and prototype declaration etc. which adds unnecessary problems in coding like making the code complex to read, debug and practice.

Designer discarded multiple inheritance to avoid the problems that occur. See this diamond problem of multiple inheritance.


Java does not support Multiple Inheritance

The above code is an example of a problem with multiple inheritance (popularly known as diamond problem; diamond with four edges). Now think, the Animal should inherit what type of swimming behaviour from its three parents Snake, Duck and Fish. It is ambiguous. For this reason, Java avoided multiple inheritance. Of course, C++ have an alternative solution. Following is the error message the compiler displays.

Java does not support Multiple Inheritance

But we know Java supports partially multiple inheritance with interfaces. Let us see the same above problem with interfaces multiple inheritance.

How the ambiguity diamond problem solved now through interfaces (an idea taken from Objective C)? Interface methods being abstract do not carry any body of implementation. So, Animal is inheriting the same three swim() methods (can I call dummy methods, fancily) from its three parents without implementation. As the method is the same, the subclass Animal gives the body as it likes. Compiler thinks all the three swim methods are overridden.

Let us see the problem through multi-level inheritance.


Java does not support Multiple Inheritance

The above swim() method prints "Swims with fins". Then how the Animal uses Duck or Snake’s swim() methods. Simply use composition as follows.

Duck d1 = new Duck();
d1.swim();

or

Snake s1 = new Snake();
s1.swim();

Another reason for avoidance is Java would like to discard the problems of object casting between super classes and subclasses, ambiguity in constructor chaining etc.

Java supports single inheritance, multi-level inheritance and hierarchical inheritance.

Pass your comments and suggestions on this tutorial " Java does not support Multiple Inheritance ".
You may be interested in the following.

1. Why Java does not support Pointers?
2. Why Java does not support operator overloading?

Leave a Reply

Your email address will not be published. Required fields are marked *