0

What are the benefits/drawbacks of using (Method 1) a separate listener classes (maybe an inner class) like:

private ClassAAL implements ActionListener
{
    ...
}
private ClassAWL implements WindowListener
{
    ...
}

versus (Method 2) implementing the interface

public class ClassA implements ActionListener, WindowListener

versus (Method 3) setting a listener using an Anonymous class for each element that needs a listener.

btn.addActionListener(new ActionListener()...);

Question: What are the Benefits and Drawbacks of each of these methods? Are there performance benefits, or any Design Patterns that recommend one over the other? or any other benefits?

I can see that:

  1. The first method is cleaner
  2. The second method is more compact
  3. The third method adds the listener code right at the element.

Note: I saw a question Nested class vs implements ActionListener on this; but most answers seem to give what the person uses rather than any advantages/disadvantages of each method.

1 Answer 1

1

If you want your listener to be more accessible (API usable), then I would recommend method 2. I also stopped using private classes a few years ago and use public static nested classes:

public class YourClass {

    public static YourNestedClass {
        //...
    }

}

There are no real performance differences in the initialization of them aside from your own implementation. If you make, say, 30 different listener objects for something that could all be done by a common object (as in method 1/2), then there may be a slight difference. Otherwise, you can really just do what you prefer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.