内部类中的构造函数(实现接口)

the*_*ace 21 java constructor anonymous-inner-class inner-classes

我将如何为实现接口的内部类编写构造函数?我知道我可以创建一个全新的课程,但我认为必须有一种方法可以做到这一点:

JButton b = new JButton(new AbstractAction() {

    public AbstractAction() {
        super("This is a button");                        
    }


    public void actionPerformed(ActionEvent e) {
        System.out.println("button clicked");
    }
}); 
Run Code Online (Sandbox Code Playgroud)

当我输入它时,它不会将AbstractAction方法识别为构造函数(编译器要求返回类型).有没有人有想法?

Ita*_*man 35

只需在扩展类的名称后插入参数:

JButton b = new JButton(new AbstractAction("This is a button") {

    public void actionPerformed(ActionEvent e) {
        System.out.println("button clicked");
    }
}); 
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用初始化块:

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");
    }
}); 
Run Code Online (Sandbox Code Playgroud)


Dav*_*ton 9

如果你因任何原因确实需要一个构造函数,那么你可以使用一个初始化块:

JButton b = new JButton(new AbstractAction() {

    {
        // Do whatever initialisation you want here.
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("button clicked");
    }
}); 
Run Code Online (Sandbox Code Playgroud)

但你不能从那里调用超类构造函数.正如Itay所说,你可以将你想要的参数传递给new.

就个人而言,我会为此创建一个新的内部类:

private class MyAction extends AbstractAction {

    public MyAction() {
        super("This is a button.");
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("button clicked");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

JButton b = new JButton(new MyAction());
Run Code Online (Sandbox Code Playgroud)