我可以在实例化匿名类时实现接口吗?
假设我有一个抽象类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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,当您指定匿名内部类的超类时,您可以指定一个普通类来扩展或接口,但不能同时指定两者。 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.
如果您的意思是下面的
Dialog
是一个界面,那么是的,可以完成。当然,
myMethod
的声明应该进入Dialog
界面。If you mean the below where
Dialog
is an interface, then yes it can be done.Of course then the declaration of
myMethod
should go into theDialog
interface.