【问题标题】:Solving the Java Interface Diamond Issue [duplicate]解决 Java 接口钻石问题 [重复]
【发布时间】:2018-08-23 15:30:09
【问题描述】:

在过去(Java 7 及之前),Java 类和接口扮演不同的角色:用于抽象方法实现的类;用于抽象对象结构的接口。但是,从 Java 8 开始,接口现在可以使用默认方法定义方法实现。这导致了一个称为“钻石问题”的问题。

带有方法execute() 的接口A 由包含execute() 的默认实现的接口BC 扩展。如果一个类随后实现了BC,则应该运行execute() 的哪个默认实现存在歧义。

interface A {
    public void execute();
}

interface B extends A {
    default void execute() { System.out.println("B called"); }
}

interface C extends A {
    default void execute() { System.out.println("C called"); }
}

class D implements B, C {
}

鉴于上面的类定义,当(new D()).execute() 被执行时,将打印什么(如果有的话):“B called”还是“C called”?

【问题讨论】:

  • 你的问题是?
  • 我投票决定将此问题作为离题结束,因为这不是一个问题。这是一种尝试记录自 Java 8 以来已知和记录在案的附带问题。
  • 刚刚编辑以正确定义问题:在运行(new D()).execute() 时,会调用来自BCexecute() 实现。
  • 这个问题不用问,用你的java编译器编译一下就行了。
  • 啊,没看到那个。

标签: java interface diamond-problem


【解决方案1】:

由于execute()D 中有两个实现,编译器将不知道要使用哪个实现。也就是说,这个程序不会编译。

决议

解决方案是D需要创建一个execute()的新实现,这样当(new D()).execute()被调用时,编译器直接在D中调用execute()而不是尝试(并且失败)找出哪个实现从BC 运行。

class D implements B, C { // D does not need to implement A, since B and C already do

    @Override
    public void execute() { // new implementation defined in A
        B.super.execute(); // calls execute() defined by B
        C.super.execute(); // calls execute() defined by C
    }

}

在本例中,(new D()).execute() 将打印 -

B called

C called

备注

如果BC 都是类,则D 不能作为BC 的子级存在,因为Java 不允许多重继承。但是,如果B xor C 是类,则D 不需要重新实现execute(),因为它是在父类中可扩展定义的。

interface B extends A {
    default void execute() { System.out.println("B called"); }
}

class C implements A {
    public void execute() { System.out.println("C called"); }
}

class D extends C implements B { 
    // Will compile correctly since C provides the implementation for execute()

}

在本例中,(new D()).execute() 将打印“C called”。

D 扩展了C,因此如果没有被覆盖,将使用C 的方法实现。

【讨论】:

  • 你的“答案”不是答案,你的第一句话是。 “答案”应该类似于“解决方案”
  • 你说得对,只是改了。
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多