• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing private variable

 
Maniganda Prakashh
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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é
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it would be something like the following :


where o1 change o2's private variable, because they are both the same class.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember, private restricts access to the class -- not the instance.
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic