Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...