interface ListenerRegistration {
void unregister();
}
List<Listener> listeners = ...;
ListenerRegistration addListener(final Listener ears)
{
class ListenerRegImpl implements ListenerRegistration {
public void unregister() {
listeners.remove(ears);
}
void register() {
listeners.add(ears);
}
}
ListenerRegImpl reg = new ListenerRegImpl();
reg.register();
return reg;
}
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".