java - Java 8 中的致命钻石

标签 java java-8

我是一名 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(); BC 都扩展了,但这不会改变结果。

关于java - Java 8 中的致命钻石,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042711/

相关文章:

java - 在 Win10 上切换 java 版本 - 注册 key 问题

java - 安卓/Java : How to get last row value in sqlite?

java - 如何在java8中对通用列表进行排序

java - 方法引用的类型是什么?

java - 是否可以从preparedStatement获取完整的请求?

java.util.Date: 7 天前

java - Optional ifPresent() 可以用在更大的表达式中以减轻对 get() 的调用吗?

使用 Lambda 的 Java 8 过滤器数组

java - Java 8 与 Java 9 中的 Stream.peek() 方法

java - 重复循环,java