为什么使用封闭class的实例,静态嵌套class无法实例化?

Why using enclosing class's instance, the static nested class can't be instantiated?

我知道可以直接访问 class 的静态成员,而不需要封闭 class 的实例。

class Outer
{
    static int a = 10;

    public static void main(String[] args)
    {
        System.out.println(a);//without using instance
    }
}

但是,同样的静态成员也可以通过 class 的实例访问。因为它们在特定 class.

的所有实例之间共享
class Outer
{
    static int a = 10;

    public static void main(String[] args)
    {
        System.out.println(new Outer().a);//with using instance
    }
}

所有这些似乎仅适用于 静态变量和静态方法 ,当尝试使用 static 嵌套 class 时,结果在编译中 error: qualified new of static class.

class Outer
{
    static class Nested
    {
        int a = 10;
    }

    public static void main(String[] args)
    {
        System.out.println(new Outer().new Nested().a);
    }
}

和其他静态成员一样,这应该也是可以的。不是吗? 是否有任何我遗漏的内部细节?

看看 this tutorial 告诉我们什么:

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.

A 只是一个 class,它没有嵌套在另一个 class.

因此,静态嵌套 class 与非嵌套 class 没有区别。在您的示例中,Nested 在行为上与 Outer 没有区别;它可以在 Outer 之外声明。因此 new Outer().new Nested() 不是有效语法。嵌套静态 class 只是为了包装方便,因此 new Outer.Nested() 可以工作,就像例如new java.util.ArrayList<String>() 有效。