java - 可以在 Java 中实例化静态嵌套类吗?

标签 java static nested instantiation

来自 Oracle 的 Java tutorials我找到了这段文字:

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();

我认为不可能实例化一个静态类,所以我不太理解粗体的句子。

你知道这意味着什么吗?

最佳答案

正如 kihero 所说,您要么将 staticabstract 混淆,要么将概念与具有 static 方法的类混淆(其中只是一个恰好有静态方法的类)。

静态嵌套类只是一个嵌套类,不需要其封闭类的实例。如果您熟悉 C++,C++ 中的所有 类都是“静态”类。在 Java 中,默认情况下嵌套类不是静态的(这种非静态种类也称为“内部类”),这意味着它们需要外部类的实例,它们在隐藏字段中在幕后跟踪该实例——但是这让内部类可以引用它们关联的封闭类的字段。

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
    }

}

How to instantiate non static inner class within a static method 上还有很多其他示例

我实际上将所有嵌套类默认声明为静态,除非我特别需要访问封闭类的字段。

关于java - 可以在 Java 中实例化静态嵌套类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18293857/

相关文章:

Java:通过反射访问对象的bean类型方法

Java 主类中只有静态成员

嵌套数组/记录的 Azure 流分析查询

Python Bottle 图像第 2 部分

java - 为什么在子类上调用在其父类(super class)中声明的静态方法时不调用子类的静态初始化程序?

sql-server - 用于 XML 路径分组的 TSQL

C++ 嵌套类,访问父变量

java - 从Java Spark到ElasticSearch的连接数

java - Ant Junit 测试陷入困境 - 需要总结

java - 是否可以将包中的所有类注册为 Spring bean