Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding equals(Object o)

Tags:

java

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?

like image 503
OneMoreVladimir Avatar asked Dec 02 '22 02:12

OneMoreVladimir


2 Answers

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.

like image 113
Vineet Reynolds Avatar answered Dec 05 '22 09:12

Vineet Reynolds


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.

like image 35
Jakub Lédl Avatar answered Dec 05 '22 10:12

Jakub Lédl