Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner class for listener in Java, is this bad practice?

Is this the right way of doing this? Iam using the MVC pattern.

in my View class, i have aButton.

Button fooButton = new Button();

public void addFooButtonListener(ActionListener foo){
    fooButton.addActionListener(foo);
}

In my Controller class constructor:

 this.theView.addFooButtonListener(new Listener());

In the Controller Class I use a inner Class named Listener

class Listener implements ActionListener {
    public void actionPerformed(ActionEvent e){
        //do whatever i want
    }
}

I have been told, that this is not the right way of doing this? is this true? If yes, what is the right way?

like image 947
Erwin Ivanov Avatar asked Feb 24 '26 23:02

Erwin Ivanov


1 Answers

As shared, your current code is perfectly fine and there is no issue in it. However, you could have used below implementations :

Anonymous Class:

new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        // To Do :: Task here
    }
}

Lambda Expressions:

button.addActionListener(e -> {
    // Task implementation here
});

Though it depends upon requirement, but the only disadvantage I can see in your implementation is the case when you have multiple button with different actions, which will end up in large amount of inner classes.

Also, if you feel that the same action can be used in different class, you can also make a separate class implementing ActionListener in maybe listeners package and then use it among all classes.

Again, that all is requirement specific and accordingly you can choose whatever suits you the best in your project.

like image 88
Aman Chhabra Avatar answered Feb 27 '26 12:02

Aman Chhabra