java - 在java中访问其类之外的私有(private)变量

标签 java visibility

以下 Java 程序编译成功。 我期望语句 y.className = "No class name."; 中出现错误 因为私有(private)变量 className 是在其类之外访问的。

class t { 

    public static void main(String[] r) {

        Y y = new Y();

        y.className = "No class name.";

        y.echoClassName();
    }   

    static class Y { 

        private String className = "Class Name is Y."; 

        public void echoClassName() {

            System.out.println(className);
        }   
    }   
}

为什么没有报错?

最佳答案

私有(private)变量的范围是包含它的整个顶级类,在您的例子中是 t。参见示例 JLS #6.6.1 (强调我的):

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

关于java - 在java中访问其类之外的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26486427/

相关文章:

java - 为什么我的 Java 骰子游戏不断重复滚动?

java - Jython:子流程模块中出现错误,AttributeError: 'module' 对象没有属性 'python'

android - 为什么 FragmentTransaction 偶尔工作?

visibility - 无锁容器和可见性

java - 使用 FragmentPagerAdapter 创建 fragment 时,在运行时更改 fragment 可见性

java - 如何在 Struts 1 中使用 Tiles2

java - 正则表达式模式可选组取决于空间

java - 如何将 .jar 依赖项包含到最终的 .aar 库文件中? (安卓工作室1.5)

Java,编译错误,构造函数

hide - EXT JS使用 "display:none"的方法是什么