Redefining Equals (Object o)

Suppose I have a class

class Key { public boolean equals(Object o) { Key k = (Key)o; return i == ki; } private int i; } 

I wonder why in the equals method I do not get an error in accessing ki due to the fact that it is private?

+4
source share
3 answers

You get access to a member from the same class. Member visibility rules apply to classes, not class objects.

To continue, the Java compiler (at compile time) and the Java virtual machine (at run time) apply the visibility rules for the object by first looking at its type.

The compiler performs this action when it has to generate byte code to access the field, call the method, and similar expressions. Access rules are applied based on the qualification type of the object, not just the object. Compiler behavior is determined by the Java language specification.

The Java virtual machine performs this operation during the binding process with the same rules defined by the Language Specification and is explicitly defined by the Virtual Machine Specification.

+14
source

You should not. The usual definition of a private member is that it is available to any other instance of the same class.

+3
source

"private" members can be accessed in a single file (same class, nested static and non-static classes).

(Of course, nested static classes need an explicit reference to the enclosing class to access private members.)

+2
source

All Articles