ปัญหา Diamond Problem
Java ไร้ Multiple Inheritance กับ Class (extends ได้แค่ 1 class) เพราะ Diamond Problem:
- Class A มี method
demo() - Class B, C extends A และ override
demo()แตกต่างกัน - Class D extends B, C (สมมติได้) → D จะมี
demo()สองแบบ → Compiler ไม่รู้เรียกไหน → Ambiguity
แก้ไขด้วย Default Methods ใน Interface (Java 8+)
- Interface สามารถมี
defaultmethod (มี implementation) - Class implements หลาย Interface ที่มี default method ชื่อซ้ำได้
- บังคับ override default method นั้นใน Class และระบุชัดเจนว่าจะเรียกของ Interface ไหน:
InterfaceName.super.defaultMethod()
ตัวอย่าง
interface MyInterface1 {
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface1");
}
}
interface MyInterface2 {
public static int num = 1000;
public default void display() {
System.out.println("display method of MyInterface2");
}
}
public class InterfaceExample implements MyInterface1, MyInterface2 {
public void display() {
MyInterface1.super.display(); // เรียกของ MyInterface1
// หรือ MyInterface2.super.display();
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
ผลลัพธ์
display method of MyInterface1 display method of MyInterface2
สรุป
Default Methods ช่วยให้ทำ Multiple Inheritance ของพฤติกรรมได้ โดย Class ที่ implements ต้อง resolve ambiguity เองด้วย InterfaceName.super.method()