File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes accessing variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "accessing variables" Watch "accessing variables" New topic

accessing variables

Naf Rash
Ranch Hand

Joined: Feb 19, 2004
Posts: 85
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

Joined: Jul 08, 2003
Posts: 24199

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:

[Jess in Action][AskingGoodQuestions]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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.

Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: accessing variables
It's not a secret anymore!