Re: How to make a globally accessible variable
Sandy wrote:
... and I WANT to be able to assign
that path to a variable which my other classes can access.
I am hoping to do this in some way so that I don't have to instantiate
an object every time just to get the path, or re-run the code to get
the path from functions that I have to then include in all the classes
that use it.
....
Basically I need to make a string variable that all my objects in the
application can access. I thought public static but either I am using
it wrong when I try to access it (it comes up null from objects other
than the one that created it) or it doesn't work as I thought it did.
You were right, you want a public static (possibly final) object.
Let us say you have a class to hold this object, call it "VariHold".
public class VariHold
{
public static String global;
}
Then in some other class (that imports VariHold) you can use an expression like
VariHold.global = derive();
and in any other subsequent logic, you can dereference VariHold.global.
Mind you, this kind of global variable is not often good practice. It is
almost always better to instantiate an object to hold this information and
pass it around.
public class VariHold
{
public String oneThing;
public String anotherThing;
}
Then your methods would take a VariHold instance as a parameter to pass your
context around.
BTW, the use of public instance variables is also bad practice, but it was
going to make the message too long to declare them as private with set...()
and get...() methods.
> I am hoping to do this in some way so that I don't have to instantiate
> an object every time just to get the path,
Why are you so averse to creating an object? It is usually the right thing to do.
- Lew