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
}
...
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With