• Post Reply Bookmark Topic Watch Topic
  • New Topic

Objects accessing each other  RSS feed

 
Vikash Agarwal
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ques: Can one object can access a private variable of another object of the same class?
Ans: 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.

I want to understand (with an example probably) how.
Please can someone help.
 
Leandro Melo
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.

This example might help you:


[ June 05, 2007: Message edited by: Leandro Melo ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a quick look at the Comparable interface and the compareTo method. This asks an object to compare itself to another object, usually another instance of the same class. It often winds up like this:

If "field1" is private, we need to access the private field of the "other" instance. And Java lets us.
 
Vikash Agarwal
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
impressive... thanks buddies !!!
 
Raghavan Muthu
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its an interesting topic .. thanks for posting it vikas and thanks to Leandro Melo and Stan James for the good example.

Is it more or less resembling like the Copy Constructor in C++. Aint I?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!