抽象超类的默认接口方法 [英] Default interface method for abstract superclass
问题描述
假设我有以下结构:
abstract class A {
abstract boolean foo();
}
interface B {
default boolean foo() { return doBlah(); }
}
class C extends A implements B {
//function foo
}
Java现在会抱怨类 C
必须从 A $ c实现抽象方法foo $ C>。
我可以通过重新定义 C
中的函数并简单地调用 B.super.foo();来解决这个问题。
。
Java will now complain that class C
must implement abstract method foo from A
.
I can work around this problem relatively easy by redefining the function in C
and simply calling B.super.foo();
.
但是我不明白为什么界面 B
的默认函数不会填写此内容要求本身,我希望能更好地理解java的基础机制。
however I do not understand why the default function from interface B
does not forfill this requirement on its own, and I would like to have a better understanding of the underlying mechanics of java.
推荐答案
答案< a href =https://stackoverflow.com/a/43943769/3185280> Jacob G. 激励我提出这个解决方案:
The answer of Jacob G. inspired me to come up with this solution:
interface Z {
abstract boolean foo();
}
abstract class A implements Z {
}
interface B extends Z {
default boolean foo() { return doBlah(); }
}
class C extends A implements B {
}
这样,类 A
的所有子类都需要定义方法 foo()
,不要求每个实现 B
的类重新实现它。
This way all subclasses of class A
are required to define a method foo()
, Without requiring every class that implements B
to re-implement it.
这篇关于抽象超类的默认接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!