[英]Can I implement an interface while instantiating an anonymous class?
Suppose I have an abstract class FactorizedDialog
. 假设我有一个抽象类
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. 正如您可能已经猜到的那样,我扩展Dialog(实际上是抽象类)只是为了向其添加方法,以便在创建匿名类时可以覆盖它。 Is it possible to implement an interface in java while I instantiate Dialog instead of using my derived abstract class?
在实例化Dialog而不是使用派生的抽象类时,是否可以在Java中实现接口?
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.
JLS第15.9节中显示的语法根本不允许两者。
If you mean the below where Dialog
is an interface, then yes it can be done. 如果您在下面是
Dialog
是接口的意思,那么可以的。
Dialog dialog = new Dialog() {
@Override
public void myMethod() {
}
}
Of course then the declaration of myMethod
should go into the Dialog
interface. 当然,
myMethod
的声明应该进入Dialog
接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.