• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Explain this!!

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I found this question in javaranch mock exam.
Can one object access a private variable of another object of the same class?
The Answer is YES. though the description was given, I could not understand it. I mean it was not clear.
Anyone! explain this!!
Sapna
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please?

Politeness will get you a lot farther than demands.
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi sapna
all the scopes like Private, Protected etc are "LEXICAL". meaning, they are textual. they ARE NOT related to objects we create.
so, if i have private int x in my class C then i can refer to variable x withing the class definition ANYWHERE regardless of which object it belongs.
eg.

this will print swapped values as we exchanged the values of c1 and c2 objects.
here we access c2.x at line 1 but still it works! why? because the access of var x is not related to the object of class C (that is c2 here) but its LEXICAL. we are referring to var x in the textual scope of class C. thats why it works.
in the S.o.p in main method i have used c1.x and c2.getX() just to show that we can access x in anyway.
if we had another class called A and private var y in that class which we wanted to use in class C's method test() then it wouldn't work.
hih
maulin
 
No one can make you feel inferior without your consent - Eleanor Roosevelt. tiny ad:
New web page for Paul's Rocket Mass Heaters movies
https://coderanch.com/t/785239/web-page-Paul-Rocket-Mass
reply
    Bookmark Topic Watch Topic
  • New Topic