Local inner classes

Instead of defining the inner class within another class, it can also be defined locally within a method:

package littletux.net.innerclass;

public class LocalInnerClass {

    private PrintManager pm;

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

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

        // Local inner class - LocalInnerClass$1LocalPrinter.class
        class LocalPrinter implements Printer {

            public void printString(String value) {
                System.err.println("LocalPrinter: " + value);
        pm.setPrinter(new LocalPrinter());

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

The interesting thing to note here is that the class is both defined and instantiated inside a method, but still available even after the scope of the defining method has been left. This can be seen as a kind of closure.