内部类中的构造函数(实现接口)
我将如何为实现接口的内部类编写构造函数?我知道我可以创建一个全新的类,但我认为必须有一种方法可以按照以下方式执行某些操作:
JButton b = new JButton(new AbstractAction() {
public AbstractAction() {
super("This is a button");
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
当我输入此内容时,它不会将 AbstractAction 方法识别为构造函数(编译器要求返回类型) 。有人有想法吗?
How would I go about writing a constructor for an inner class which is implementing an interface? I know I could make a whole new class, but I figure there's got to be a way to do something along the line of this:
JButton b = new JButton(new AbstractAction() {
public AbstractAction() {
super("This is a button");
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
When I enter this it doesn't recognize the AbstractAction method as a constructor (compiler asks for return type). Does anyone have an idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需在扩展类的名称后面插入参数即可:
另外,您可以使用初始化块:
Just insert the parameters after the name of the extended class:
Also, you can use an initialization block:
如果您出于某种原因确实需要构造函数,那么您可以使用初始化块:
但是您不能从那里调用超类构造函数。正如 Itay 所说,您可以将所需的参数传递给 new 的调用。
但就我个人而言,我会为此创建一个新的内部类:
然后:
If you really need a contructor for whatever reason, then you can use an initialization block:
But you can't call a super-class constructor from there. As Itay said though, you can just pass the argument you want into the call to new.
Personally though, I would create a new inner class for this:
then:
生成的类不是
AbstractAction
类型,而是扩展/实现AbstractAction
的某种(未命名、匿名)类型。因此,这个匿名类的构造函数需要具有这个“未知”名称,而不是AbstractAction
。这就像正常的扩展/实现:如果您定义一个
class House extends Building
并构造一个House
,您将构造函数命名为House
而不是构建
(或AbstractAction
只是为了回到原来的问题)。The resulting class is not of type
AbstractAction
but of some (unnamed, anonymous) type that extends/implementsAbstractAction
. Therefore a constructor for this anonymous class would need to have this 'unknown' name, but notAbstractAction
.It's like normal extension/implementation: if you define a
class House extends Building
and construct aHouse
you name the constructorHouse
and notBuilding
(orAbstractAction
just to com back to the original question).编译器抱怨的原因是因为您试图在匿名类中声明一个构造函数,而匿名类不允许这样做。正如其他人所说,您可以通过使用实例初始值设定项或将其转换为非匿名类来解决此问题,这样您就可以为其编写构造函数。
The reason the compiler is complaining is because you are trying to declare a constructor inside your anonymous class, which is not allowed for anonymous classes to have. Like others have said, you can either solve this by using an instance initializer or by converting it to a non-anonymous class, so you can write a constructor for it.