• Post Reply Bookmark Topic Watch Topic
  • New Topic

accessing variables  RSS feed

 
Naf Rash
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any way of accessing a variable that is in a public method of another class.
I know that you can create an object of the other class and invoke methods from that clas but do not know if the value of a variable within a method can be 'accessed'. If you can could you please provide me an example.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variables local to a method -- i.e., the variable "x":

can't be directly accessed outside of the method that declares them. They don't even exist when the method isn't being executed.
But if you think you need to do this, it's just a design problem you can easily overcome. First, you may simply be able to change the method to return the value of interest.

If this isn't possible -- perhaps because the method already returns some other value -- then another option is to make the variable a member of the class, and provide an accessor for it:

 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are you trying to do where you need to access a local variable? If you can describe the problem you are trying to solve, someone here should be able to suggest possible solutions to your problem.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!