I'm a Java developer and I've been learning C++ on the side. I recently got into the "deadly diamond of death" in C++ and researched if this problem was possible in Java. In Do interfaces solve the "deadly diamond of death" issue?, I found this:
Java 8 screws this up for methods; an interface now can declare both
default methods and static method implementations. This brings a large
chunk of the Diamond of Death problem into the language.
I'm wondering if someone would be able to expand on the problems introduced by Java 8 for the DDD.
解决方案
I imagine the quoted answer is referring to scenarios such as this in Java:1
interface B {
default void x() { System.out.println("B::x"); }
}
interface C {
default void x() { System.out.println("C::x"); }
}
class D implements B, C {}
What would something like new D().x() do here?
Luckily, the compiler forbids the definition of D entirely, with the following message:
D inherits unrelated defaults for x() from types B and C
One can resolve the ambiguity (and satisfy the compiler) by overriding x in D. One may then explicitly invoke the individual inherited default methods:
class D implements B, C {
@Override
public void x() {
B.super.x(); // Note explicit interface names
C.super.x();
}
}
1. Clearly, there's no diamond here. But this is an even simpler case. We could add interface A { void x(); } that both B and C extend, but that wouldn't change the result.