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 Access variables set in main from other classes? .. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Access variables set in main from other classes? .." Watch "Access variables set in main from other classes? .." New topic

Access variables set in main from other classes? ..

Ron Mullen

Joined: May 24, 2007
Posts: 2
Hi all,

I am trying to adapt someone else's code, whilst learning Java at the same time, and am completely stumped. The situation is as follows:

I have variables in the main class for a program which I need to use in a class created later on in the program structure. How can I access these variables? I posted this question earlier ( where people kindly suggested the idea of using a get method in main. But I cannot see how you call the method in main -- any ideas?

I've started to create some dummy code which I'm trying to get to work before I tackle the actual problem. I've included it all below, so you can see my thinking on this:

NB As you can see from the code below, I don't really have much of an idea of how to code in Java -- any help/suggestions would be of great use!

As such, any ideas? Any small hints to get me on the right track would be of great use. Is there a quick way to get variables out of main, through get methods? If so, how you reference the "main" class to get the variables? Is there a standard Java way of referening main?

Needless to say, you can probably see the desperation here, so any/all help would be of tremendous help.

Thanks in advance.



Edit by mw: Added Code Tags to keep formatting intact.
[ June 14, 2007: Message edited by: marc weber ]
marc weber

Joined: Aug 31, 2004
Posts: 11343

When you run what's shown here, not much will happen because there's only one main method, and all it does is create an instance of PassingVariables. My guess is that you will want to create an instance of Tester and actually call the methods in that class.

When you declare a variable, you need to give it a value before trying to use it. For example, in the method getVarFromMain(), you declare PassingVariables p; but never assign it a value.

Also, you've got a lot going on here that makes it difficult to isolate and test the behavior. Here's a simple demo that focuses on the issue...

[ June 14, 2007: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: Access variables set in main from other classes? ..
It's not a secret anymore!