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

标签 java java-8 default-method

假设我有以下结构:

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/

相关文章:

java - 有没有办法将默认构造函数添加到接口(interface)

Java:在同一个接口(interface)的另一个默认方法中调用一个默认方法

java - Maven 目标未附加到阶段

java - 如何在Linux上获得用户定义的系统颜色?

java - Hibernate @Filter 未应用于关联

java - Spring+Hibernate+Cassandra的组合如何运行

Java GC 日志充满了奇怪的字符

java-8 - Runtime.getRuntime().maxMemory() 计算方法

datetime - 如何检查当前时间实例之前或之后的截止时间?

java - 从匿名内部类调用重写的默认方法