Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private Variables

 
Amit Lonkar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following is the question on the www.javaranch.com/game.jsp. Please can some one tell me how this is possible.
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.
Thanks
Amit
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here you go.

Main constructs a new PrivateTest, and is able to access a private member of that class. It also creates a second object of the same class, and passes this as an argument to a method in the first object. The printanInt() method is able to access the private member of another object, because both objects are of the same class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic