This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: Can statically nested classes be instantiated in Java?

From Oracle’s Java tutorial, I found the following:

Like class methods and variables, statically nested classes are associated with their external classes. Like static class methods, a statically nested class cannot directly refer to instance variables or methods defined in its enclosing class – it can only use them through object references.

Note: A statically nested class interacts with instance members of its external class (and other classes) just like any other top-level class. In effect, a statically nested class is a top-level class nested within another top-level class for easy packaging.

Accessing a statically nested class with a closed class name:

OuterClass. StaticNestedClass class

For example, to create an object for a statically nested class, use the following syntax:

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

I don’t think it’s possible to instantiate a static class, so I’m not sure what this means.

Do you know what that means?

Answer a

You either confuse static and abstract, as Kihero said, or you confuse a class with a static method (which happens to have static methods).

A statically nested class is simply a nested class that does not require its enclosing class instance. If you’re familiar with C++, all classes in C++ are “static” classes. In Java, nested classes are not static by default (this non-static variant is also called an “inner class”), which means that they require instances of the outer class, which they track in hidden fields — but this allows the inner class to reference the fields of its associated closed class.

public class Outer {

    public class Inner {}public static class StaticNested {}public void method (a) {
        // 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 (a) {
        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(a); // ok: 'o' is the enclosing instance}}Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/1…