07 September 2011

Java Inline Class Definitions

Here's something in Java I came across the other day that I didn't know about: non-anonymous inline class definitions.

interface ListenerRegistration {
   void unregister();

List<Listener> listeners = ...;

ListenerRegistration addListener(final Listener ears)
   class ListenerRegImpl implements ListenerRegistration {
      public void unregister() {

      void register() {

   ListenerRegImpl reg = new ListenerRegImpl();
   return reg;

Just as with an anonymous inline class, this class can access final variables in outside scopes, etc.
But more, this class:
  • can be declared anywhere in the block it is used, not necessarily at the top, just as with class definitions declared inside other classes
  • retains its type information allowing access to added fields and methods

This is especially useful when you need to return an instance implementing an interface, but want to use a concrete class. If the class is not used anywhere outside the scope of instantiation, the class can be defined inline, and added methods and fields are now known instead of having to use only a reference to the implemented interface.

Obviously, this example is to demonstrate a point and not the simplest way to implement the above 'addListener'. It's also not "always a good thing" as with most idioms and design patterns, use a good an appropriate tool for the job you have to accomplish.

Just another affirmation that "you don't know a language unless you program in it for 10 years".