jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Accessing private variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing private variable" Watch "Accessing private variable" New topic

Accessing private variable

Maniganda Prakashh

Joined: Oct 01, 2005
Posts: 9
Can one object access a private variable of another object of the same class?
Answer is given yes. But I couldn't understand the question. How can one object access other object's private variable? Please give me an example code.
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

I think it would be something like the following :

where o1 change o2's private variable, because they are both the same class.

[My Blog]
All roads lead to JavaRanch
marc weber

Joined: Aug 31, 2004
Posts: 11343

Remember, private restricts access to the class -- not the instance.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Bill Cruise
Ranch Hand

Joined: Jun 01, 2007
Posts: 148
Good answer, Marc. I had a couple of students confused by this just yesterday. The example code was:

The most common answer to this is that student's tend to gloss over the point that b needs to access a's private data. Some catch it and say that the code won't compile. Sadly, the ones with the sharper eyes are wrong. Access modifiers are at the class level, not the object level.

[ June 01, 2007: Message edited by: Bill Cruise ]

[ June 01, 2007: Message edited by: Bill Cruise ]
[ June 01, 2007: Message edited by: Bill Cruise ]
I agree. Here's the link: http://aspose.com/file-tools
subject: Accessing private variable
jQuery in Action, 3rd edition