以下 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/