Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access my private variables of the "other" object directly, in my equals(Object o) method

In Java in the equals(Object o) method I can access the private variables of the passed in object without going through its public getters.

public boolean equals(Object o){     ...     MyObject other = (MyObject)o;     return getProp() == other.prop;  } 

How's that?

like image 935
non sequitor Avatar asked Oct 17 '09 05:10

non sequitor


People also ask

Can a private variable be accessed from a object?

We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself.

Can you use equals () with objects?

The equals() method is a static method of the Objects class that accepts two objects and checks if the objects are equal. If both the objects point to null , then equals() returns true .

Can you access private variables in the same class?

the private field is accessible in the class/object in which the field is declared. It is private to other classes/objects outside of the one it is located in.


2 Answers

Private data is accessible by any instance of that class, even if one instance of class A is accessing the private members of another instance of A. It's important to remember that that access modifiers (private, protected, public) are controlling class access, not instance access.

like image 64
cletus Avatar answered Sep 24 '22 06:09

cletus


The probable answer is that the designer of the visibility model considers that any developer working in a class has to master the implementation of the whole class.

But this is a bad idea. This encourages bad practice. A developer accessing a field of Person, in the class Person, does not have to know the implementation of the whole class. The good practice is to use the accessor, without having to know what operations the accessor does.

like image 34
Nicolas Barbulesco Avatar answered Sep 25 '22 06:09

Nicolas Barbulesco