What is the diamond problem in multiple inheritance, and how does Java handle it?
The Diamond Problem: It occurs in multiple inheritance when a class inherits from two classes that have a common base class. This can create ambiguity about which inherited method to execute.
Example (in other languages):
class A {
void display() {
System.out.println("Class A");
}
}
class B extends A {}
class C extends A {}
class D extends B, C { // Ambiguity: which 'display()' method to call? }
How Java Handles It: Java avoids the diamond problem by not supporting multiple inheritance with classes. Instead, Java uses interfaces to achieve multiple inheritance. If a class implements multiple interfaces with default methods having the same name, the ambiguity must be resolved explicitly.
Example:
interface A {
default void display() {
System.out.println("Interface A");
}
}
interface B {
default void display() {
System.out.println("Interface B");
}
}
class C implements A, B {
@Override
public void display() {
// Resolving the conflict explicitly
A.super.display();
B.super.display();
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.display();
}
}