I got this question in the Java Rules Round up. (#208)Can one object access a private variable of another object of the same class? Answer: Yes Private means "private to the class"; NOT "private to the object". So two objects of the same class could access each other's private data. Shouldn't this be NO! Take this for example
p1 and p2 are objects of the same class and they cannot access private members of each other. If I change the private class to this
Now both p1 and p2 are objects of the same class and they can access the private variable num, this is because they are in the same class as the private variable num. Could someone please confirm that I'm looking at this question correctly and that the answer should be NO!
...if the member ... is declared private, then access is permitted if and only if it occurs within the body of the top level class (�7.6) that encloses the declaration of the member.
So, let me give an example:
In this code snippet, an instance of the class Private is accessing a private member of another instance (of the same type). This is allowed because, as stated in the JLS, the access is contained to the body of the class that defines the member. That's the key to the whole question. In order to say that class A is accessing a member of class B, one would assume that the access is occurring within the body of class A. As, in this special case, class A and class B are the same, access to private members is allowed. It's a rather odd question, but I'd go along with the answer given. I hope that helps, Corey
Corey thanks for the response. I was looking at the question wrong. I was thinking that the question should of specified if the object are in the same class or not. However because it did not specify if the objects are inside or outside the class that declares the private variables then the question is worded OK. I guess I just have to read the question more carefully. Thanks for your help