gpt4 book ai didi

java - 从接口(interface)中的默认方法访问 super 方法

转载 作者:行者123 更新时间:2023-11-30 07:09:50 26 4
gpt4 key购买 nike

我在摆弄 Java 8 并归结为以下代码,我认为它可以工作:

class UnrelatedClass implements UnrelatedInterfaceDefault {
@Override
public void unrelate2() {
System.out.println("Unrelated");
}
}

interface UnrelatedInterfaceDefault extends UnrelatedInterfaceOne, UnrelatedInterfaceTwo {
default public void unrelate() {
UnrelatedInterfaceOne.super.unrelate2();
UnrelatedInterfaceTwo.super.unrelate2();
}
}

interface UnrelatedInterfaceOne {
public void unrelate2();
}

interface UnrelatedInterfaceTwo {
public void unrelate2();
}

UnrelatedInterfaceOne.super.unrelate() 上,我得到错误:

abstract method unrelate2() in UnrelatedInterfaceOne cannot be accessed directly.

但考虑一下,如果我要创建一个实现 UnrelatedInterfaceDefault 的类,那么我实际上确实UnrelatedInterfaceOneUnrelatedInterfaceTwo< 的实现,所以它可以工作吗?

为什么在这种情况下会出现这个特定的编译器错误?

最佳答案

这是失败的,因为您的接口(interface)中的方法是抽象的。如果您将其设为 default,那么我猜它会编译。不过,我现在无法对其进行测试。

来自 JLS §15.12.3 - Compile-Time Step 3: Is the Chosen Method Appropriate? :

If the form is TypeName . super . [TypeArguments] Identifier, then:

  • It is a compile-time error if the compile-time declaration is abstract.

另请注意,使用 super 调用方法永远不会通过动态调度。它不会调用覆盖的方法,而只会调用 super 类中定义的方法,或者在本例中为 TypeName

关于java - 从接口(interface)中的默认方法访问 super 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22632527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com