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?
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.
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 .
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.
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.
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.
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