Difference between static nested class and regular class

主宰稳场 提交于 2019-12-30 09:56:13

问题


I know this is a bit of a duplicate question but I want to ask it in a very specific way in order to clarify a very important point. The primary question being: Is there any difference at all between otherwise identical classes when one is a static nested class and the other is a regular, top-level, class other than access to private static fields in a containing class?

// ContainingClass.java
public class ContainingClass {
    private static String privateStaticField = "";

    static class ContainedStaticClass {
        public static void main(String[] args) {
            ContainingClass.privateStaticField = "new value";
        }
    }
}

// OutsideClass.java
public class OutsideClass {
    public static void main(String[] args) {
        ContainingClass.privateStaticField = "new value";  // DOES NOT COMPILE!!
    }
}

In other words: Is the only, ONLY difference, between what ContainedStaticClass can access or do and what OutsideClass can access or do, the fact that OutsideClass cannot access ContainingClass.privateStaticField directly? Or are there other, subtle differences that aren't commonly discussed or ran into?


回答1:


Your statement is correct: the only difference between a static class and and a outer class is access to the class and the members of the enclosing class. The static keyword is declaring that the class is not an inner class: it is in effect an outer class within the scope of the enclosing class.

See https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.5.1




回答2:


ContainedStaticClass has package private (i.e. default) visibility and OutsideClass has public visibility.

You could have chosen to make ContainedStaticClass protected or private which were not options for OutsideClass.




回答3:


A subtle difference is that a nested class has the ability to shadow members of the enclosing type:

class ContainingClass {
    public static String privateStaticField = "a";

    static class ContainedStaticClass {
        public static String privateStaticField = "b";
        public static void main(String[] args) {
            System.out.println(privateStaticField);  // prints b
        }
    }
}

But that's also related to the scope of the class.



来源:https://stackoverflow.com/questions/30335937/difference-between-static-nested-class-and-regular-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!