can one object access a private variable of another object of the same class?
Tushar Kherde
Ranch Hand
Joined: Apr 28, 2006
Posts: 56
posted
0
can one object access a private variable of another object of the same class?
the answer on this site is yes. and explanation given is:
private means 'private to the class not to the object' so 2 objects of the same class can access each others private data.
your question is not clear . if one or two objects are craeted for a class(say A) inside A, then the objects can acces private property . if a object lies outside the class(A), then private variable is not visible to the object.
Raj Kamal wrote:The answer is Yes. Check out the simple example below.
This example does *not* do what the original poster is asking about--p1 is not accessing anything private in p2. p1 calls a public method--after that, the private method is being invoked by p2.
I agree that the private method is being invoked on p2, or a reference of it. I could try to explain my reasoning for concluding one object access a private variable of another object of the same class. In the example I call invoke() from inside the Class Private (using a different object reference) I am able to access the same and there is no violation of any sort. But if I try to do the same from outside the Class definition the compiler would not permit. It can be demonstrated easily by adding
p2.display();
inside the main method. This would result in a compilation error:-
display() has private access in Private
I feel if I had added the above statement the relevance of the example would be better understood.
Cheers,
Raj.
Sateesh.B Kumar
Greenhorn
Joined: Sep 05, 2007
Posts: 6
posted
0
Not sure what exactly your question means. As you are aware one cannot access private variable of an object.
The situation like one you outilne occurs when you have a method in the class which takes a reference
to object of the same class as an argument.
See the below code snippet which overrides the "equals" method. Here the private variable
of the passed object is being referred.
Raj Kamal wrote:The question is whether does 'private' mean Private to an object/class. I'd rather go with the latter. To be more specific, its private to a Class?
Yes. Private means private to the class -- of which, the previous example by Sateesh, clearly demonstrates.