"Can one object access a private variable of another object of the same class?"
The answer is Yes, with the explanation that private means "private to the class" and NOT "private to the object".
Is that correct? I thought an object cannot (directly) access its own private variables even, how should it be able to access the private variables of another object?
Do I misunderstand the question?
Thanks for your help, Anatol
Joined: Sep 16, 2005
Boi, if an object couldn't access its own private data, we are in big trouble
If you don't believe what question 80 claims, write some code to test your suspicions. It should only take a minute and you'll learn from the exercise! Test before you post... [ November 10, 2005: Message edited by: Jeff Albrechtsen ]
Private members are implementation details which only the class itself knows about. Any instance knows this, and because all instances use the same code within a JVM they know all other instances share the same implementation, and hence the same private members.
Good reasoning, but ultimately, it is that way by fiat. In Smalltalk, you might say that fields are all protected, since a subclass can directly access superclass fields, but one instance of X cannot access any fields in another instance of X. That's just how the language is defined.
Where is one House object is accessing the private variable of the other House object? Is it in this line:
>> houseB.numberOfChairs = houseA.numberOfChairs;
But we are simply assigning integer values, is an object accessing another object?
It is assigning integer values yes. However, these integer values are private members (variables) of two different objects. Here it is not an object accessing the private variable but a class accessing the private variables of instances of that same class.