Diamond problem — D kế thừa từ B và C, cả 2 đều extends A và override cùng method.
Gọi d.method() → version nào?
A
/ \
B C ← cả 2 override A.method()
\ /
DC++ giải quyết bằng virtual inheritance phức tạp; Java né bằng 2 quyết định:
1. Cấm multiple class inheritance — class D extends B, C {} không compile.
2. Interface cho phép multiple implementation. Trước Java 8 không có code → không xung đột. Java 8 thêm default method → diamond quay lại:
interface B { default void m() { System.out.println("B"); } }
interface C { default void m() { System.out.println("C"); } }
class D implements B, C {
// ❌ compile error nếu không override
@Override public void m() { B.super.m(); } // bắt buộc — chỉ định rõ
}Cú pháp mới (Java 8): Interface.super.method() — gọi default của interface cha cụ thể.
Quy tắc resolve khi không cần override:
1. Class beats interface — class thắng nếu cùng có method.
2. Subtype beats supertype — version cụ thể hơn thắng.
3. Bằng nhau → compile error, buộc dev override.
Java ưu tiên explicit > implicit: không tự đoán, hoặc cấm cú pháp, hoặc bắt dev override.
The diamond problem — D inherits from B and C, both extending A and overriding the same method.
Calling d.method() → which version?
A
/ \
B C ← both override A.method()
\ /
DC++ resolves it with complex virtual inheritance; Java avoids it with two decisions:
1. Forbid multiple class inheritance — class D extends B, C {} does not compile.
2. Interfaces allow multiple implementation. Pre-Java 8 had no code → no conflict. Java 8 added default methods → diamond returns:
interface B { default void m() { System.out.println("B"); } }
interface C { default void m() { System.out.println("C"); } }
class D implements B, C {
// ❌ compile error without an override
@Override public void m() { B.super.m(); } // required — pick explicitly
}New syntax (Java 8): Interface.super.method() — call a specific parent interface's default.
Resolution rules when no override needed:
1. Class beats interface — class wins when both have the method.
2. Subtype beats supertype — the more specific version wins.
3. Tie → compile error, forcing the developer to override.
Java prefers explicit over implicit: never guesses — either forbids the syntax or forces an override.