静态嵌套类和常规类之间的区别 [英] Difference between static nested class and regular class

查看:71
本文介绍了静态嵌套类和常规类之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个重复的问题,但是我想以一种非常具体的方式提出这个问题,以便阐明一个非常重要的观点。主要的问题是:如果一个相同的类是静态嵌套类,而另一个是常规的顶层类,而不是访问包含类中的私有静态字段,那么这些相同的类之间是否有任何区别?

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

换句话说:这是唯一的区别, ContainedStaticClass 可以访问或执行的操作与 OutsideClass 可以访问或执行的操作之间, OutsideClass 无法直接访问 ContainingClass.privateStaticField 吗?还是有其他通常不会讨论或遇到的细微差别?

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?

推荐答案

您的陈述是正确的:唯一的区别在静态类与外部类之间的访问是访问该类及其所在类的成员。 static 关键字声明该类不是内部类:实际上,它是封闭类范围内的外部类。

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.

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

这篇关于静态嵌套类和常规类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆