Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing varaibles from another class.

 
Naf Rash
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose that there are 2 separate classes. Is it possible to access some variable that is in a private method of the other class? If so could you please provide me an example of how this could be done?
 
Eddie Vanda
Ranch Hand
Posts: 283
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Naf,
You have a couple of problems.
Things are declared private so people cannot access it from any other classes.(not sure about extending though)
Method variables are stored on stack only while that method is running.
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally speaking... "No you can't". Private methods can't be accessed from any other class, except from the class they are located in (Even if they were subclassed).


However you should know that in the case of inner classes it will be a different story, see code:
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As stated, the answer to your question is "no." However, if you describe what you want to do in more detail (perhaps with some code to illustrate), we may be able to suggest a solution that uses the tools that Java provides.
Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic