Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Should ActionListeners, KeyListeners, Etc, Always Be Declared In Inner Classes?

In all the Java source code examples I have looked at the listeners have always been declared in inner classes.

Why - what is the reason for coding the classes like this instead of having the listener(s) in their own seperate *.java file \ class?

Would having seperate classes for the listeners be considered a bad design?

If it's not a bad design \ sackable offence could someone please post a short example demonstrating how to implement this?

Thank for reading.

Edit\Update - 10.8.2010: Thanks to all who took the time to reply. Lots of insightful points to consider. Having read all the answers I think that unless there is a very good reason for doing otherwise it is better and easier to declare listeners as inner classes.

Apologies for not coming back to this question sooner, but I don't always have as much time for coding as I'd like :-(

Happy coding.

like image 346
The Thing Avatar asked Aug 08 '10 22:08

The Thing


2 Answers

Good reasons for using inner classes:

  • Avoids adding extra top-level classes to your package namespace
  • Keeps the code locally encapsulated (e.g. within the component that requires the event handling behaviour)
  • static inner classes work well when they do not need to access fields of the enclosing class

Possible reasons for using top level classes:

  • You have a special type of listener that you expect to be used by external packages or forms part of your API (e.g. in the Java class library itself)
  • The listener is used in many places, and is not logically specific to any one of many possible enclosing classes

In short: inner classes are usually preferred, but if you have good reasons then it can be perfectly sensible to create top level classes instead.

like image 81
mikera Avatar answered Oct 14 '22 00:10

mikera


No, I don't think they should always be inner classes. It implies that the UI itself always knows how to make the best choice of listener.

Another way to look at it might be that Listeners are injected into the UI. Maybe they're provided by the Controller, which instantiates the UI and tells it how to react to UI events.

I think this is more of a dependency injection view of the world. There may be important advantages to it.

like image 37
duffymo Avatar answered Oct 13 '22 23:10

duffymo