Domanda

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
    }
...
}
È stato utile?

Soluzione 2

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.

Altri suggerimenti

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.

If you use an anonymous class, the code becomes more readable, but you may not re-utilize it.

So, I would only use an anonymous class if it's short and I'm absolutely sure that I'll not have to use it again anywhere.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top