Access variables set in main from other classes? ..
Joined: May 24, 2007
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 (http://www.coderanch.com/t/407156/java/java/Command-line-arguments-passed-main) 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 ]
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 sscce.org