Why does Java, C# etc. doesn’t support multiple inheritance?

December 26, 2017


Modern languages like Java, C# doesn’t support multiple inheritance. But its predecessors like C++ supports it. Then what is the reason multiple inheritance is no longer possible now?

What is multiple inheritance?

In multiple inheritance, a class inherits its properties from two or more classes. This can be well explained with the help of this diagram.

(Multiple inheritance)

Why multiple inheritance is a headache?

Consider the scenario where class A is the base class of class B and class C, and a fourth class D that inherits from class B and class C.
Consider the case if class B and class C overrides the method of class A. Since class D inherits from two classes i.e. class B and class C, it creates an ambiguity which implementation of the overridden method to be used in class D.
In this image, Class A has a method named foo().
Class B and Class C inherits from Class A and overrides the implementation of foo() in their own way.
But when Class D inherits from Class B and Class C, this leads to a confusion which overridden implementation to use in Class D. Whether it should be Class B: foo() or Class C: foo().

Although C++ provides a way to solve this problem, still the solution is ambiguous to programmers in the way it behaves.
Hence, multiple inheritance has been removed and is no more a part of Java and C#.

Alternative to multiple inheritance

Although, multiple inheritance is no more a part of Java and C# but still, there is a way we can implement the same along with resolving the ambiguity of the above-explained problem.

The solution to the problem is interfaces.

The only way to implement multiple inheritance is to implement multiple interfaces in a class.

For this to be done for the Classes represented above, the structure would be like:




interface A { void foo(); } interface B { void foo(); } interface C { void foo(); } Class D implements Class B,Class C { void foo() { Print(“Hello Everybody”); } }
This way, modern languages like C#, Java can support multiple inheritance without creating a headache for developers.

You Might Also Like

0 comments