当我编写以下代码时,编译器如何不报错?
public class MyClass
{
private int count;
public MyClass(int x){
this.count=x;
}
public void testPrivate(MyClass o){
System.out.println(o.count);
}
}
即使它是编写 testPrivate
的同一类的实例,它不应该在 System.out.println(o.count) 处给出编译错误
?毕竟,我是在尝试直接访问私有(private)变量。
代码甚至运行良好。
最佳答案
可以从声明它的类中的任何方法访问私有(private)成员,无论该方法是访问其自己的 (this
) 实例的私有(private)成员还是某个其他实例的私有(private)成员。
这在 JLS 6.6.1 中有说明:
...Otherwise, if the member or constructor is declared private, then 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 的这一特性允许您编写接受类实例作为参数的方法(例如 - clone(Object other)
、compareTo(Object other)
) 不依赖于对所有需要访问的私有(private)属性具有非私有(private) getter 的类。
关于java - 这个私有(private)变量如何访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482579/