Constructors in Inner classes (implementing Interfaces)

thepandaatemyface picture thepandaatemyface · Jun 15, 2010 · Viewed 15.4k times · Source

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?

Answer

Itay Maman picture Itay Maman · Jun 15, 2010

Just insert the parameters after the name of the extended class:

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

    public void actionPerformed(ActionEvent e) {
        System.out.println("button clicked");
    }
}); 

Also, you can use an initialization block:

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");
    }
});