Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java action listener: implements vs anonymous class

I am trying to teach myself Java and had a question that I wasn't able to answer so far. In some of my reading online I have found two ways of using action listener that seem to do the same thing. But I am trying to figure out what is the advantage/disadvantage of one over the other.

Is it better to use anonymous class like this:

public MyClass() {
...
    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            //doSomething
        }
    });
...
}

or is it best to implement at the beginning of the class like so:

public MyClass() implements ActionListener {
...
    myButton.addActionListener(this);

    public void actionPerformed(ActionEvent e) {
        //doSomething
    }
...
}
like image 523
noob - HREF Avatar asked Oct 02 '22 16:10

noob - HREF


2 Answers

Only if your class really is an ActionListener (is-a relationship) and will be used as an ActionListener somewhere else, it should implement ActionListener.

If it is just used internally as an ActionListener, implementing ActionListener would leak implementation details to the API of the class. Use composition in that case (has-a relationship).

This is true for other interfaces and superclasses as well.

like image 118
Puce Avatar answered Oct 05 '22 11:10

Puce


This comes down to a style thing really. Both will perform exactly the same way in code.

The separate class will tend to keep the code inside your actual method simpler, whereas the anonymous inner class brings the code for the listener implementation within the method which can make it clearer what it is doing.

There is also the case that anonymous inner classes can access final variables in the method that creates them. You can't do that with a pre-written class (although you can pass the variables into the controller).

The separate code is re-usable - so if you have the same listener in multiple places then it is the clear winner.

like image 33
Tim B Avatar answered Oct 05 '22 13:10

Tim B