假设有两个接口Interface1
和Interface2
where Interface2
extends Interface1
。
interface Interface1 {
default void method() {
System.out.println("1");
}
// Other methods
}
interface Interface2 extends Interface1 {
@Override
default void method() {
System.out.println("2");
}
// Other methods
}
假设我想创建一个实现的类,Interface2
但我想method()
成为Interface1
. 如果我写
class MyClass implements Interface1, Interface2 {
public void method() {
Interface1.super.method();
}
}
我得到编译错误:
默认超级调用中的错误类型限定符:冗余接口 Interface1 由 Interface2 扩展
可以通过创建第三个接口来解决这个问题:
interface Interface3 extends Interface1 {
default void method() {
Interface1.super.method();
}
}
然后:
class MyClass implements Interface1, Interface2, Interface3 {
public void method() {
Interface3.super.method();
}
}
这编译得很好,如果我实例化一个 newMyClass
并调用method()
,输出是1
预期的。
所以我的问题是,鉴于很容易绕过只能InterfaceName.super.method()
为链中最具体的接口编写的限制,限制的原因是什么?一开始就禁止你写作可以防止哪些问题Interface1.super.method()
?