Anonymous inner classes

A more subtle type of local inner classes is the anonymous inner class. Using this approach, it is not even necessary to explicitly define a class – the class is defined and instantiated in one step, by creating an instance of an interface or a subclass of another class and then implementing or overriding any methods as necessary:

package littletux.net.innerclass;

public class AnonymousInnerClass {

    private PrintManager pm;

    public static void main(String[] args) {
        AnonymousInnerClass app = new AnonymousInnerClass();
        app.initApp(); // anonymous inner class is defined locally here ...
        app.runApp(); // ... but is still available here!!
    }

    private void initApp() {
        pm = new PrintManager();

/*****************************************************************/
        // Anonymous inner class - AnonymousInnerClass$1.class
        pm.setPrinter(new Printer() {

            @Override
            public void printString(String value) {
                System.err.println("AnonymousPrinter: " + value);
            }
        });
    /*****************************************************************/
    }

    private void runApp() {
        pm.print("Hello World");
    }
}

A usual usage of anonymous inner classes is the definition of AWT/Swing event listeners. Similar to the local inner class, the instance of the anonymous inner class is still available later even after the scope where the class was defined has been left. This is also very similar to the concept of a closure. We will have a closer look to closures in an upcoming article.