如何重写抽象内部类的方法?

发布于 2024-12-20 06:49:03 字数 651 浏览 3 评论 0原文

我的代码是:

core/Base.java

package core;
public class Base {
    public abstract class AbstractInner {
        abstract void run();
    }
}

Test.java

class Test extends core.Base {
    class Inner extends AbstractInner {
        void run() {}
    }
}

javac 抱怨如下;

shell> javac -cp . Test.java 
Test.java:2: Test.Inner is not abstract and does not override abstract method run() in core.Base.AbstractInner
    class Inner extends AbstractInner {
    ^

我的错误是什么?

如果Base和Test在同一个包中,则编译成功。我不知道为什么。

My codes are:

core/Base.java

package core;
public class Base {
    public abstract class AbstractInner {
        abstract void run();
    }
}

Test.java

class Test extends core.Base {
    class Inner extends AbstractInner {
        void run() {}
    }
}

javac complains like the following;

shell> javac -cp . Test.java 
Test.java:2: Test.Inner is not abstract and does not override abstract method run() in core.Base.AbstractInner
    class Inner extends AbstractInner {
    ^

What is my mistake?

If Base is in the same package as Test, compile is successful. I don't know why.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我入戏太深 2024-12-27 06:49:03

有一些非直观的规则来管理包私有成员的重写。本质上,如果重写的类位于同一个包中,则可以重写包私有方法。如果不是,则它无法看到 AbstractInnerrun() 声明,因此无法覆盖它。相反,您正在声明一个具有相同签名的新方法。

如果您在 AbstractInner 中将 run() 设为受保护(或公共)(因此也在 Inner 中),而不是使用默认可见性,则它将按预期工作。

回想一下,只有在接口中才隐式声明方法public。在抽象类中,它们隐式是包私有的。

There are some non-intuitive rules governing overridibility of package-private members. Essentially, you can override a package-private method if the overriding class is in the same package. If it's not, it does not have visibility to see AbstractInner's declaration of run() and so can't override it. Instead you are declaring a new method with the same signature.

If you make run() protected (or public) in AbstractInner (and thus in Inner as well) instead of using the default visibility, it will work as intended.

Recall that only in interfaces are declared methods implicitly public. In abstract classes, they are implicitly package-private.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文