Suppose I have a class
c开发者_运维百科lass Key {
public boolean equals(Object o) {
Key k = (Key)o;
return i == k.i;
}
private int i;
}
I wonder why in equals method I do not get error about accessing k.i because of its being private?
You are accessing the member from the same class. Member visibility rules apply to classes, not to objects of the class.
To expand on this further, the Java compiler (at compile time), and the Java Virtual Machine (at runtime) apply the visibility rules on an object by first looking at it's type.
The compiler performs this activity, when it has to generate byte code for field access, method invocation and similar expressions. The access rules are applied based on the qualifying type of the object, and not the object alone. The behavior of the compiler is defined by the Java Language Specification.
The Java Virtual Machine performs this activity during the process of linking, with the same rules defined by the Language Specification, and explicitly defined by the Virtual Machine Specification.
You're not supposed to. The usual definition of a private member is that it is accessible to any other instance of the same class.
"private" members can be accessed in the same file (same class, nested static and non-static classes).
(Of course nested static classes need an explicit reference to the enclosing class to access the private members.)
精彩评论