The difference between a static nested class and a regular class

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 main question is: is there any difference between other identical classes if one is a static nested class and the other is a regular top-level class other than access to private static fields in the 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: The only single difference between what ContainedStaticClasscan be obtained or done, and what OutsideClasscan be accessed or done, the fact that OutsideClassit cannot be accessed ContainingClass.privateStaticFielddirectly? Or are there other subtle differences that are not usually discussed or found?

+4
3

ContainedStaticClass ( ), OutsideClass .

, ContainedStaticClass , OutsideClass.

+2

, shadow :

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
        }
    }
}

.

+1
source

Source: https://habr.com/ru/post/1588874/


All Articles