java 死亡,Java 8中致命的死亡钻石

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值