gpt4 book ai didi

java - 抽象父类(super class)的默认接口(interface)方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:17:03 26 4
gpt4 key购买 nike

假设我有以下结构:

abstract class A {
abstract boolean foo();
}

interface B {
default boolean foo() { return doBlah(); }
}

class C extends A implements B {
//function foo
}

Java 现在会提示类 C 必须从 A 实现抽象方法 foo。通过在 C 中重新定义函数并简单地调用 B.super.foo();,我可以相对轻松地解决这个问题。

但是我不明白为什么接口(interface) B 中的默认函数本身不能满足这个要求,我想更好地了解 java 的底层机制。

最佳答案

接口(interface)中的默认方法用于防止在向接口(interface)添加方法时破坏依赖于接口(interface)的程序。

在您描述的情况下,不清楚接口(interface)中的默认方法(按设计必须稍后添加)是否真正履行了抽象类最初设想的契约。

在这种情况下,Java 提示会更安全。

以上文字是我对9.4.1.3 of the JLS SE8 spec中段落的解读,我引用:

Similarly, when an abstract and a default method with matching signatures are inherited, we produce an error. In this case, it would be possible to give priority to one or the other - perhaps we would assume that the default method provides a reasonable implementation for the abstract method, too. But this is risky, since other than the coincidental name and signature, we have no reason to believe that the default method behaves consistently with the abstract method's contract - the default method may not have even existed when the subinterface was originally developed. It is safer in this situation to ask the user to actively assert that the default implementation is appropriate (via an overriding declaration).

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

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