静态嵌套类

时间:2013-08-02 15:17:17

标签: java class static nested

我正在阅读'思考Java',我遇到了一些奇怪的例子(对我而言)

class StaticTest {
    static class StaticClass {
        int i = 5;
    }
}

public class I {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        StaticTest.StaticClass t = new StaticTest.StaticClass();
    }

}

如何创建静态类的实例?是否有一些例外情况“您无法创建静态类的实例”?

提前致谢

4 个答案:

答案 0 :(得分:1)

对于类,修饰符static描述外部类和内部类之间的关系。

如果内部类不是静态的,则它绑定到外部类的实例,并且不能从外部创建。

静态内部类可以在没有外部类实例的情况下完全创建,但具有对该类成员的特权访问权。

答案 1 :(得分:0)

static类只不过是一个类,但与它的代码放置位置有所不同。

因此,您可以创建静态类的实例。唯一的区别是你必须提供类的名称,它嵌套static一个(如你的代码片段所示)。

StaticTest.StaticClass t = new StaticTest.StaticClass();

答案 2 :(得分:0)

Java docs关于为静态嵌套类创建实例。

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.

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

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

答案 3 :(得分:0)

在这种情况下,static描述了b / w内部和外部类

的关系

它并不意味着内部类是静态的

静态嵌套类不会调用非静态方法或访问嵌套它的类实例的非静态字段