J4102
J4102

Reputation: 473

Method inside Parameter? Java Swing

There is a problem not with my program but with the weird concept of Java so to speak. What is the code below doing? Is the method acting as the parameter of the forums method? I know it is literally adding an action listener object that really isn't defined much and then it is somehow separating the last parameter parenthesis in the back of the squiggly brackets? I don't understand how this would work. Please explain if you can in-depth.

forums.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

    }
});

Upvotes: 1

Views: 334

Answers (1)

javac
javac

Reputation: 2441

This is an anonymous class. You could easily have written

public class ForumActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }
}

// ...

forums.addActionListener(new ForumActionListener());

However, by using an anonymous class like this:

forums.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }
}

you create an action listener that is an instance of an unnamed (anonymous) class that implements the ActionListener interface and overrides a method in it. This allows you to easily create objects with different behavior which are only used once.

Upvotes: 2

Related Questions