访问实例对象的私有字段 [英] Access private field of a instance object
问题描述
我有一个类,其中有一个名为 orbit
的字段(它的类型与我的类 Body
相同>并具有私有
修饰符):
I have a class, which has one field named orbits
(it has the same type as my class Body
and has the private
modifier):
public class Body {
// I defined it as private field
private Body orbits = null;
public Body getOrbits(){
return orbits;
}
public void setOrbits(Body orbits){
this.orbits = orbits;
}
public void capture(Body victim){
//Why 'victim' can access 'orbits' ?
victim.orbits = this;
}
}
在课堂上,我定义了一个名为<$的方法c $ c> capture(身体受害者),其中有一个类型为 Body
的参数。我想知道为什么我可以直接访问实例受害者的
?我的意思是该字段是私人
字段 orbit
private
,是不是通过实例受害者无法访问?
In the class, I defined a method named capture(Body victim)
, which has one parameter with type Body
. I am wondering in the method why I can directly access the private
field orbits
of instance victim
? I mean the field is private
, isn't it non-accessible through the instance victim?
推荐答案
隐私不是每个实例 - 它是每个类。
Privacy is not per instance - it's per class.
该类可以访问所有实例的私有字段。
The class can access the private fields of all instances.
例如,方法 equals(Object o)
可以将o(如果适用)转换为相同的类型,并将其私有成员与调用equals()的对象进行比较。
For example, the method equals( Object o )
can cast o (if appropriate) to the same type, and compare its private members with the object on which equals() was called.
这篇关于访问实例对象的私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!