Can a static nested class be instantiated in Java?

user1031431 picture user1031431 · Aug 18, 2013 · Viewed 27.3k times · Source

From Oracle's Java tutorials I've found this text:

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

I thought it is not possible to instantiate a static class, so I don't really understand the sentence in bold.

Do you have any idea what it means?

Answer

Jason C picture Jason C · Aug 18, 2013

You are either confusing static with abstract as kihero says, or you are muddling the concept with a class that has static methods (which is just a class that happens to have static methods).

A static nested class is just a nested class that doesn't require an instance of its enclosing class. If you are familiar with C++, all classes in C++ are "static" classes. In Java, nested classes are not static by default (this non-static variety is also called an "inner class"), which means they require an instance of their outer class, which they track behind the scenes in a hidden field -- but this lets inner classes refer to fields of their associated enclosing class.

public class Outer {

    public class Inner { }

    public static class StaticNested { }

    public void method () {
        // non-static methods can instantiate static and non-static nested classes
        Inner i = new Inner(); // 'this' is the implied enclosing instance
        StaticNested s = new StaticNested();
    }

    public static void staticMethod () {
        Inner i = new Inner(); // <-- ERROR! there's no enclosing instance, so cant do this
        StaticNested s = new StaticNested(); // ok: no enclosing instance needed

        // but we can create an Inner if we have an Outer: 
        Outer o = new Outer();
        Inner oi = o.new Inner(); // ok: 'o' is the enclosing instance
    }

}

Lots of other examples at How to instantiate non static inner class within a static method

I actually declare all nested classes static by default unless I specifically need access to the enclosing class's fields.