Why Java Does Not Support Multiple Inheritance Explained
multiple inheritance with classes to avoid the diamond problem, which causes ambiguity when methods have the same signature in multiple parent classes. Instead, Java uses interfaces to achieve multiple inheritance of type safely without ambiguity.Syntax
Java allows a class to inherit from only one parent class using the extends keyword. To inherit multiple types, Java uses interfaces with the implements keyword.
Class inheritance syntax:
class ChildClass extends ParentClass { }Interface inheritance syntax:
class ChildClass implements Interface1, Interface2 { }class Parent1 { void show() { System.out.println("Parent1 show method"); } } class Parent2 { void show() { System.out.println("Parent2 show method"); } } // This will cause a compile-time error in Java // class Child extends Parent1, Parent2 { } interface Interface1 { void display(); } interface Interface2 { void display(); } class Child implements Interface1, Interface2 { public void display() { System.out.println("Child display method"); } }
Example
This example shows how Java avoids multiple inheritance with classes but allows multiple interfaces. The Child class implements two interfaces and provides its own method implementation to avoid ambiguity.
interface Printable { void print(); } interface Showable { void print(); } class Document implements Printable, Showable { public void print() { System.out.println("Document print method"); } } public class Main { public static void main(String[] args) { Document doc = new Document(); doc.print(); } }
Common Pitfalls
Trying to inherit from two classes with the same method causes the diamond problem, which Java avoids by disallowing multiple class inheritance. A common mistake is attempting class Child extends Parent1, Parent2, which causes a compile error.
Using interfaces requires the implementing class to define the method, resolving ambiguity.
class Parent1 { void greet() { System.out.println("Hello from Parent1"); } } class Parent2 { void greet() { System.out.println("Hello from Parent2"); } } // Wrong: causes compile error // class Child extends Parent1, Parent2 { } interface Greet1 { void greet(); } interface Greet2 { void greet(); } class Child implements Greet1, Greet2 { public void greet() { System.out.println("Hello from Child"); } }
Quick Reference
- Single inheritance: Use
extendswith one class only. - Multiple inheritance of type: Use
implementswith multiple interfaces. - Diamond problem: Avoided by disallowing multiple class inheritance.
- Interface methods: Must be implemented by the class to resolve conflicts.