Static nested classes

In the previous example, if you want to instantiate the inner class within a static method (e.g. the main method), this does not work (for the same reason described in the previous section when trying to instantiate the inner class from within another class):

...
public static void main(String[] args) {
    InnerPrinter ip = new InnerPrinter();
    ...
}
...
No enclosing instance of type InnerClass is accessible.
Must qualify the allocation with an enclosing instance of type InnerClass
(e.g. x.new A() where x is an instance of InnerClass)

Since we do not have an enclosing instance available, we can use a static inner class like in the following example:

package littletux.net.innerclass;

    public class StaticInnerClass {

    /*****************************************************************/
    // Inner class - StaticInnerClass$StaticInnerPrinter.class
    static class StaticInnerPrinter implements Printer {

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

    public static void main(String[] args) {
        PrintManager pm = new PrintManager();

/*****************************************************************/
        pm.setPrinter(new StaticInnerPrinter());
        pm.print("Hello World");
/*****************************************************************/
    }
}

Note that in this case, the inner class is bound to the class of the enclosing type – since no instance of the enclosing type needs to exist, the inner class does not have access to members of the enclosing class.