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".


  1. I too just discover this last week. (I don't do extensive Java for my work, however)

    I'm surprise why many people keep moaning for the lack of closure in Java. The workaround is trivial.

  2. Clearly, you haven't read Kathy Sierra's preparation book for the SCJP. :-) Preparing for (and achieving) the SCJP is an outstanding opportunity to learn more about the language than you ever really wanted to know.

  3. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
    Vee Eee Technologies

  4. it's good to see this information in your post, i was looking the same but there was not any proper resource, thanx now i have the link which i was looking for my research.
    source: www.wbupdates.com