我是一名 Java 开发人员,同时我一直在学习 C++。我最近研究了 C++ 中的“致命钻石”,并研究了这个问题在 Java 中是否可能出现。在 Do interfaces solve the "deadly diamond of death" issue? ,我发现了这个:
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.
我想知道是否有人能够扩展 Java 8 为 DDD 引入的问题。
最佳答案
我想象 quoted answer指的是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 {}
new D().x()
会在这里做什么?
幸运的是,编译器完全禁止定义 D
,并显示以下消息:
D inherits unrelated defaults for x() from types B and C
可以通过重写 D
中的 x
来解决歧义(并满足编译器的要求)。然后可以显式调用各个继承的默认方法:
class D implements B, C {
@Override
public void x() {
B.super.x(); // Note explicit interface names
C.super.x();
}
}
<子>1。显然,这里没有钻石。但这是一个更简单的案例。我们可以添加 interface A { void x();
B
和 C
都扩展了,但这不会改变结果。
关于java - Java 8 中的致命钻石,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042711/