我如何能够在 class 中引用实例的私有字段?
How is it that I am able to reference private fields of an instance inside a class?
我曾寻找过解释,但没能找到。为什么这段代码有效?具体来说——为什么可以访问实例的私有成员?据我所知,只有在原始 class.
中的方法中创建实例时,它才有效
public class MyClass {
private int thing;
public MyClass () {}
public MyClass makeMe () {
MyClass myClass = new MyClass();
myClass.thing = 1;
return myClass;
}
}
私有字段只能由 class 访问。您仍在 MyClass
的实例中操作,因此您无需使用 setter.
即可看到和访问私有字段
更正式一点...JLS 6.6.1谈论访问。
这是删节的片段,强调我的:
A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
- ...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.
public MyClass makeMe () {
MyClass myClass = new MyClass();
myClass.thing = 1;
return myClass;
}
在 MyClass
class 的 内部 ,因此它可以访问私有成员。
我曾寻找过解释,但没能找到。为什么这段代码有效?具体来说——为什么可以访问实例的私有成员?据我所知,只有在原始 class.
中的方法中创建实例时,它才有效public class MyClass {
private int thing;
public MyClass () {}
public MyClass makeMe () {
MyClass myClass = new MyClass();
myClass.thing = 1;
return myClass;
}
}
私有字段只能由 class 访问。您仍在 MyClass
的实例中操作,因此您无需使用 setter.
更正式一点...JLS 6.6.1谈论访问。
这是删节的片段,强调我的:
A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
- ...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.
public MyClass makeMe () {
MyClass myClass = new MyClass();
myClass.thing = 1;
return myClass;
}
在 MyClass
class 的 内部 ,因此它可以访问私有成员。