Java 内部类中的构造函数(实现接口)
如何为实现接口的内部类编写构造函数?我知道我可以创造一个全新的课堂,但我想一定有办法做到这一点:Java 内部类中的构造函数(实现接口),java,constructor,inner-classes,anonymous-inner-class,Java,Constructor,Inner Classes,Anonymous Inner Class,如何为实现接口的内部类编写构造函数?我知道我可以创造一个全新的课堂,但我想一定有办法做到这一点: JButton b = new JButton(new AbstractAction() { public AbstractAction() { super("This is a button"); } public void actionPerformed(ActionEvent e) {
JButton b = new JButton(new AbstractAction() {
public AbstractAction() {
super("This is a button");
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
当我输入这个时,它不会将AbstractAction方法识别为构造函数(编译器要求返回类型)。有人知道吗?只需在扩展类的名称后插入参数:
JButton b = new JButton(new AbstractAction("This is a button") {
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
此外,还可以使用初始化块:
JButton b = new JButton(new AbstractAction() {
{
// Write initialization code here (as if it is inside a no-arg constructor)
setLabel("This is a button")
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
JButton b = new JButton(new AbstractAction() {
{
// Do whatever initialisation you want here.
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
结果类不是
AbstractAction
类型,而是扩展/实现AbstractAction
的某些(未命名、匿名)类型。因此,此匿名类的构造函数需要具有此“未知”名称,而不是AbstractAction
这就像普通的扩展/实现:如果你定义一个
类房屋扩展建筑并建造一个房屋你命名的是建筑商房屋,而不是建筑(或者抽象动作,只是为了回到原来的问题)。如果你真的出于任何原因需要一个建筑商,然后可以使用初始化块:
JButton b = new JButton(new AbstractAction() {
{
// Write initialization code here (as if it is inside a no-arg constructor)
setLabel("This is a button")
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
JButton b = new JButton(new AbstractAction() {
{
// Do whatever initialisation you want here.
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
但是不能从那里调用超级类构造函数。正如Itay所说的,您可以将所需的参数传递到对new的调用中
但就我个人而言,我会为此创建一个新的内部类:
private class MyAction extends AbstractAction {
public MyAction() {
super("This is a button.");
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
}
然后:
编译器抱怨的原因是您试图在匿名类中声明构造函数,这是匿名类不允许的。正如其他人所说,您可以通过使用实例初始值设定项或将其转换为非匿名类来解决此问题,这样您就可以为其编写构造函数。当您达到匿名内部类所能做的极限时,这就强烈提示您应该改为编写普通内部类。