Inner classes

A normal inner class is simply defined within the class of another class, as shown below.

package littletux.net.innerclass;
   public class InnerClass {

    private PrintManager pm;

    /*****************************************************************/
    // Inner class - InnerClass$InnerPrinter.class
    class InnerPrinter implements Printer {

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

    public static void main(String[] args) {
        InnerClass app = new InnerClass();
        app.initApp();
        app.runApp();
    }

    private void initApp() {
        pm = new PrintManager();
        /*****************************************************************/
        pm.setPrinter(new InnerPrinter());
        /*****************************************************************/
    }

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

It is also possible to make the inner class private, which is a useful pattern for hiding implementation details. If the inner class is not private (means, has default access or public access) it can be instantiated from other classes with a somewhat specific syntax: 

The intuitive way would be to call something like

InnerClass.InnerPrinter ip = new InnerClass.InnerPrinter();

However, since inner classes (means, non-static nested classes) always require an instance, this does not work – we require an instance of the enclosing class and then need to call the new operator on this instance:

InnerClass ic = new InnerClass();
InnerClass.InnerPrinter ip = ic.new InnerPrinter();