This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi All. This is a question I got while attempting the Round Up questions in JavaRanch. Q) Can one object access a private variable of another object of the same class ? I answered NO & got it wrong. (thats why I am here!) Here's the answer that was given at the end of the questions... A) 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. -------- As per me, the above would make sense if the variable in question was a STATIC variable. But, if its an INSTANCE variable we are talking about, then I believe, each object(instance of the class) has its own (seperate) copy of that variable (Hence the term Instance variable). And Correct me if I am wrong, Private Instance variables are neither shared nor can be accessed from different objects of the same class. Since this question is threatening my basics, I would appreciate any help. thanks. Himanshu
JLS 6.6.8 talks about that but "private" really means private to the class and not to the object even if the member is an instance variable. ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform
Hi. Thanks for your reply, Valentin. Can you please gimme a working example of a private instance variable (belonging to one object, say A) & being accessed by another object B, of the same class. That would make things more clear. Thanks in advance. Himanshu
Joined: Aug 26, 2001
There you go
output: i of t2 is:3 j of t2 is:4 i of t1 is:1 j of t1 is:2
Let me know if it's still not clear HIH ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform [This message has been edited by Valentin Crettaz (edited October 31, 2001).]
HTH, - Manish [This message has been edited by Manish Hatwalne (edited October 31, 2001).]
Joined: Aug 01, 2001
Thanks both ! I was thinking on some other lines... I was thinking how can one access the private member of one object from a second object without referring to the second object in any way. In both your examples, YOU are still accessing the Private variable of the first object using the First object, itself. (Inside the function). In other words, if I view the main() function of the code, yes, I did get object 2's private variable's value from Object 1... but if I look deeper, it is actually the same Object accessing its OWN data. (Since the object is being passed as a parameter to the function.) Thanks for the help ! I think I got what I was looking for. - Himanshu.