问题描述
编写以下代码时编译器如何不抱怨?
How is the compiler not complaining when I write the following code?
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)
中给出编译错误?毕竟,我试图直接访问私有变量。
代码甚至运行正常。
Even though it is an instance of the same class in which testPrivate
is written, shouldn't it give a compilation error at System.out.println(o.count)
? After all, I am trying to access a private variable directly.
The code even runs fine.
推荐答案
私有成员可以从声明它的类中的任何方法访问,无论该方法是否访问自己的( this
)实例的私有成员或其他实例的私有成员会员。
A private member is accessible from any method within the class in which it is declared, regardless of whether that method accesses its own (this
) instance's private member or some other instance's private member.
这在:
Java的这个特性允许你编写接受类实例作为参数的方法(例如 - clone(Object other)
, compareTo(Object other)
)而不依赖于具有非私有getter的类,用于所有需要的私有属性要访问。
This feature of Java allows you to write methods that accept an instance of the class as an argument (for example - clone(Object other)
, compareTo(Object other)
) without relying on the class having non private getters for all the private properties that need to be accessed.
这篇关于这个私有变量怎么可以访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!