Java 8默认方法继承 [英] Java 8 default method inheritance
问题描述
假设有以下类型:
public interface Base {
default void sayHi(){
System.out.println("hi from base");
}
}
public interface Foo extends Base {
@Override
default void sayHi(){
System.out.println("hi from foo");
}
}
public interface Bar extends Base {
}
public class MyClass implements Foo, Bar {
public static void main(String[] args) {
MyClass c = new MyClass();
c.sayHi();
}
}
在这种情况下,如果执行main
,打印hi from foo。为什么 Foo
的实现优先?不 Bar
从 Base
继承 sayHi()
,因为如果 MyClass
只是实现 Bar
,那么 Base
实施会被称为?因此,代码仍然无法编译是有意义的。另外,因为 Bar
应该有 Base
的 sayHi()$ c的实现$ c>,为什么我不能在
MyClass
中覆盖它,如:
In this scenario, if main
is executed, "hi from foo" is printed. Why does Foo
's implementation take precedence? Doesn't Bar
inherit sayHi()
from Base
, since if MyClass
was to only implement Bar
, the Base
implementation would be called? So it would make sense for the code to still not compile. Also, since Bar
should have Base
's implementation of sayHi()
, why can't I override it in MyClass
like:
@Override
public void sayHi() {
Bar.super.sayHi();
}
尝试这样做时出现以下错误:
The following error occurs when trying to do so:
错误类型限定符默认超级调用方法中的条形,在Foo中重写sayHi()
bad type qualifier Bar in default super call method, sayHi() is overridden in Foo
推荐答案
使用 JLS 9.4.1 ,只是更改了一些名称:
This behavior is specified using almost your exact example in JLS 9.4.1, just with some names changed around:
interface Top {
default String name() { return "unnamed"; }
}
interface Left extends Top {
default String name() { return getClass().getName(); }
}
interface Right extends Top {}
interface Bottom extends Left, Right {}
从Top继承name(),但Bottom从Left继承name(),
不是Right。这是因为Left中的name()会覆盖Top中name()的声明
。
Right inherits name() from Top, but Bottom inherits name() from Left, not Right. This is because name() from Left overrides the declaration of name() in Top.
JLS不会似乎给出了我能看到的任何特别具体的理由;这就是Java设计者决定继承的方式。
The JLS doesn't seem to give any especially concrete reason that I can see; this is just how the Java designers decided inheritance would work.
这篇关于Java 8默认方法继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!