Java 8中致命的死亡钻石 [英] Deadly Diamond of Death in Java 8
问题描述
我是一名Java开发人员,我一直在学习C ++。我最近在C ++中进入了致命的死亡钻石,并研究了这个问题是否可能在Java中出现。在界面是否解决了致命的死亡之钻问题?,我发现了这个:
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为方法搞砸了;现在,接口可以声明
默认方法和静态方法实现。这会带来一大块
的钻石死亡问题。
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引入的问题。
I'm wondering if someone would be able to expand on the problems introduced by Java 8 for the DDD.
推荐答案
我想引用的答案指的是Java中的这种情况: 1
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 {}
什么会像新的D()。x()
在这里做什么?
What would something like new D().x()
do here?
幸运的是,编译器禁止完全定义 D
,并带有以下消息:
Luckily, the compiler forbids the definition of D
entirely, with the following message:
D inherits unrelated defaults for x() from types B and C
可以解决歧义(并满足编译器)通过在 D
中覆盖 x
。然后可以显式调用各个继承的默认方法:
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。显然,这里没有钻石。但这是一个更简单的案例。我们可以添加接口A {void x(); }
同时 B
和 C
扩展,但这不会改变结果。
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.
这篇关于Java 8中致命的死亡钻石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!