wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes private instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "private instance variables" Watch "private instance variables" New topic
Author

private instance variables

Ryan Wilson
Ranch Hand

Joined: Apr 16, 2003
Posts: 65
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!
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
From the JLS, §6.6.1 Determining Accessibility:

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


SCJP Tipline, etc.
Ryan Wilson
Ranch Hand

Joined: Apr 16, 2003
Posts: 65
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
 
 
subject: private instance variables
 
Similar Threads
Question about classes and static keyword
Can one object access a private variable of another object of the same class?
JavaRanch Rule Round-up Game Query ??
protected access
Question from http://www.javaranch.com/game.html...