我可以在实例化匿名类时实现接口吗?

发布于 2025-01-07 18:47:26 字数 537 浏览 4 评论 0原文

假设我有一个抽象类FactorizedDialog。它看起来像这样(请注意,这只是一些虚拟示例)

public abstract class FactorizedDialog extends Dialog {

  public abstract void myMethod();
} 

现在我可以做这样的事情:

FactorizedDialog dialog = new FactorizedDialog() {

            @Override
            public void myMethod() {
                // implementation here
            }
}

正如您可能已经猜到的那样,我扩展 Dialog (实际上是一个抽象类)只是为了向其添加一个方法,这样我就可以当我创建匿名类时覆盖它。当我实例化 Dialog 而不是使用派生的抽象类时,是否可以在 java 中实现接口?

Suppose I have an abstract class FactorizedDialog. It looks like this (please note that this is just some dummy example)

public abstract class FactorizedDialog extends Dialog {

  public abstract void myMethod();
} 

Now I can do something like this:

FactorizedDialog dialog = new FactorizedDialog() {

            @Override
            public void myMethod() {
                // implementation here
            }
}

As you may have guessed I extend Dialog (which is in fact an abstract class) only to add a method to it so I can override it when I create an anonymous class. Is it possible to implement an interface in java while I instantiate Dialog instead of using my derived abstract class?

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

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

发布评论

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

评论(2

枯寂 2025-01-14 18:47:26

不,当您指定匿名内部类的超类时,您可以指定一个普通类来扩展接口,但不能同时指定两者。 JLS 第 15.9 节中显示的语法根本不允许两者兼而有之。

No, when you specify the superclass of an anonymous inner class you can either specify a normal class to extend or an interface, but not both. The syntax shown in section 15.9 of the JLS simply doesn't allow for both.

丑丑阿 2025-01-14 18:47:26

如果您的意思是下面的 Dialog 是一个界面,那么是的,可以完成。

Dialog dialog = new Dialog() {

    @Override
    public void myMethod() {
    }
}

当然,myMethod 的声明应该进入Dialog 界面。

If you mean the below where Dialog is an interface, then yes it can be done.

Dialog dialog = new Dialog() {

    @Override
    public void myMethod() {
    }
}

Of course then the declaration of myMethod should go into the Dialog interface.

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