我完全不明白为什么这行不通:
interface Test {
default void doMagic() {
System.out.println("Abracadabra");
}
}
class TestImpl implements Test {
}
class SpecialTestImpl extends TestImpl {
public void doMagic() {
Test.super.doMagic(); // Error: No enclosing instance of the type Test is accessible in scope
}
}
这是一些奇怪的 Eclipse 错误消息吗(它也无法处理 Lamdas,所以也许 Mars 还没有完全准备好 Java 8)?
我可以通过让SpecialTestImpl
实施Test
直接(这会产生警告,因为没有必要)或重写中的方法TestImpl
(出于同样的原因,会产生警告)。
那么为什么我不能调用 super 方法呢?
我的猜测是因为如果我能够打电话Test.super.doMagic()
直接执行该方法TestImpl
会破坏 APISpecialTestImpl
尽管不应该。但如果我让的话这也是真的SpecialTestImpl
实施Test
并以这种方式调用默认方法。
这不是 Eclipse 错误,而是预期行为。只需使用super.doMagic();
,效果很好。您不能致电Test.super.doMagic()
正如后来的doMagic()
可以重新实现在TestImpl
超类。在这种情况下TestImpl
实施必须完全影子Test
实施使其无法访问。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)