问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/1581478/why-can-i-access-my-private-variables-of-the-other-object-directly-in-my-equa