Possible Duplicate:
Global variables in Java
How to create a list of global variables that can be accessible from different classes? Should I create a class of global variables...?
Possible Duplicate:
Global variables in Java
How to create a list of global variables that can be accessible from different classes? Should I create a class of global variables...?
you can say
public class GlobalVariables{
public static final Integer INT_VAR=12;
public static final String STR_VAR="abcd";
// public static final List<SomeObject> someObjectList=new ArrayList<SomeObject>()// this can be populated using some method later.
}
you can also use interface
s and enum
s for declaring global variables..
Personally, I would create a class containing public static variables and then use import static MyClass.*
in each class the variables are required.
import static MyClass.*;
class MainClass {
void someMethod() {
// using "import static" there's no need to do
// int x = MyClass.SomeStaticInt;
int x = SomeStaticInt;
System.out.println(x);
}
}
Should I create a class of global variables...?
Yes. create a static class having public static final
fields.
final
will mark those fields as constants.
you can create one class called ConstantCodes.java
Now declare your variable in this class has follows,
public class ConstantCodes
{
public static String PublicVariable = "I am public variable";
}
Now you can above variable anywhere from your project using below line,
String myStr = ConstantCodes.PublicVariable;