📘 Lesson · Lesson 33
Why No Multiple Inheritance
Why No Multiple Inheritance
The Diamond Problem
Java does NOT allow a class to extend two classes. This avoids the diamond problem — confusion when two parents have the same method.
Interfaces Solve It
interface A { default void show(){ System.out.println("A"); } }
interface B { default void greet(){ System.out.println("B"); } }
class C implements A, B { } // multiple interfaces - allowed!
C c = new C();
c.show(); c.greet();A
B
Summary
- Java blocks multiple class inheritance to avoid the diamond problem.
- A class can implement multiple interfaces instead.
Diamond Problem
Java एक class को दो classes extend करने नहीं देता। यह diamond problem से बचाता है — जब दो parents में एक ही method हो तो confusion।
Interfaces इसे हल करते हैं
interface A { default void show(){ System.out.println("A"); } }
interface B { default void greet(){ System.out.println("B"); } }
class C implements A, B { } // multiple interfaces - allowed!
C c = new C();
c.show(); c.greet();A
B
सारांश
- Java diamond problem से बचने को multiple class inheritance रोकता है।
- Class कई interfaces implement कर सकती है।