Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

java - Difference between static nested class and 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...