Originally posted by Sayed Ibrahim Hashimi:
I don't think this is a violoation of encapsulation(although some may disagree). The whole idea of encapsulation and data hiding is to prevent objects from modifying when they don't know exactly what they are dealing with. For example if I had a class that contained an int, this int would be private and I would make public get/set methods for it.
Assume that this class has a set of listeners associated with it that would need to be notified that its value has changed. Objects of different classes may not know about this but certainly objects of the same class know, so its ok to let them take care of it. In the sample that I provided you in the changeOther() method it would also have to notify those liseteners.
I hope this makes sense, and also hope that too many people won't disagree.
Originally posted by Randy Nichols:
But wouldn't that also be a reason for wanting it to NOT be visible, so I could put "setter" and "getter" methods on the object where I'd put the notify code, and make sure others don't access the private members without my knowing?
Originally posted by Joe Nguyen:
Let forget about class perspective for a moment and discuss about general OO practice.
Suppose there is a class Person and let create two instances of the class Person. One is John and the other is Michelle. It would not be right to let John directly modifies Michelle's favorite sport without letting michelle knows (assume favoriteSport is a private variable of class Person).
As long as direct access to private variable is permitted, the other object does not need/want to invoke getter/setter method.
If the Person class is public, everyone can create instances of the class; this is where unwanted side effects may take place.