Why doesn't Java support Multiple Inheritance?

Modified on Tue, 28 Mar, 2023 at 4:04 PM

Problem Manifestation: The diamond problem is a common problem that arises when we use multiple inheritance in object-oriented programming. It occurs when a class inherits from two different classes, which in turn inherit from the same class. This creates a diamond- shaped inheritance hierarchy which can lead to ambiguity in method resolution.


Understand the problem: Java does not support multiple inheritance because it can create ambiguity in method resolution. When two classes with the same method signature are inherited by a third class, the compiler is unable to decide which method to call. This results in a compile- time error.


Code Example:



class A {

public void foo() {

System.out.println("A's foo");

}

}


class B extends A {

public void foo() {

System.out.println("B's foo");

}

}


class C extends A {

public void foo() {

System.out.println("C's foo");

}

}

class D extends B, C { // This will give a compile-time error

// Code here

}


    

Debugging the problem:


To avoid the diamond problem, Java allows for the use of interfaces, which can be implemented by multiple classes. This allows for the creation of a diamond-shaped inheritance hierarchy without any ambiguity in method resolution.


Extra Information:


It is important to note that while Java does not support multiple inheritance, it does support multi-level inheritance, where a class can inherit from another class, which in turn inherits from another class. This avoids the diamond problem while still allowing for a more complex inheritance hierarchy.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article