使用祖父接口的默认方法 [英] Using The Default Method Of Grandparent Interface

查看:106
本文介绍了使用祖父接口的默认方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全失去了为什么这不行:

I'm totally lost on why that won't work:

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
    }
}


$ b $这是一个奇怪的Eclipse错误信息(它也不能应付Lamdas,所以也许火星不是完全Java 8准备好了)?

Is this some weird Eclipse error message (it's not able to cope with Lamdas either, so maybe Mars isn't entirely Java 8 ready, yet)?

我可以通过让 SpecialTestImpl 实现测试直接(它产生一个警告,因为它是不必要的)或覆盖 TestImpl (由于相同的原因而产生警告)的方法。

I can fix it by letting SpecialTestImpl implement Test directly (which yields a warning, because it's unnecessary) or overriding the method in TestImpl (which yields a warning for the same reasons).

那么为什么我不能调用超级方法?

So why wouldn't I be able to call the super method?

我的猜测是因为如果我能直接调用 Test.super.doMagic(),实现方法在 TestImpl 将破坏 SpecialTestImpl 的API,尽管它不应该。但是如果我让 SpecialTestImpl 实现测试并调用默认方式,那也是如此。

My guess was because if I was able to call Test.super.doMagic() directly, implementing the method in TestImpl would break the API for SpecialTestImpl even though it shouldn't. But that is also true if I let SpecialTestImpl implement Test and call the default method that way.

推荐答案

这不是一个Eclipse bug,它是预期的行为。只需使用 super.doMagic(); ,它工作正常。您可以在 Test.super.doMagic()中调用 doMagic()可以在<$ c中重新实现$ c> TestImpl 超类。在这种情况下, TestImpl 实现必须完全影响 Test 实现,使其无法访问。

It's not an Eclipse bug, it's expected behavior. Just use super.doMagic();, it works fine. You cannot call the Test.super.doMagic() as later the doMagic() can be reimplemented in TestImpl superclass. In this case the TestImpl implementation must completely shadow the Test implementation making it inaccessible.

这篇关于使用祖父接口的默认方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆