Suppose I have a class
class 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With