How do you define Global variables in Java ?
If you need to update global property, a simple getter/setter wrapper class can be used as global variable. A typical example is shown below.
public class GlobalHolder {
private static final GlobalHolder INSTANCE = new GlobalHolder();
private volatile int globalProperty;
public static GlobalHolder getInstance() {
return INSTANCE;
}
public int getGlobalProperty() {
return globalProperty;
}
public void setGlobalProperty(int globalProperty) {
this.globalProperty = globalProperty;
}
public static void main(String[] args) {
GlobalHolder.getInstance().setGlobalProperty(10);
System.out.println(GlobalHolder.getInstance().getGlobalProperty());
}
}
Another way is to create an interface like this:
public interface GlobalConstants
{
String name = "Chilly Billy";
String address = "10 Chicken head Lane";
}
Any class that needs to use them only has to implement the interface:
public class GlobalImpl implements GlobalConstants
{
public GlobalImpl()
{
System.out.println(name);
}
}
There is no global variable in Java
Nevertheless, what we do have is a static
keyword and that is all we need.
Nothing exists outside of class in Java. The static
keyword represents a class variable that, contrary to instance variable, only has one copy and that transcends across all the instances of that class created, which means that its value can be changed and accessed across all instances at any point.
If you need a global variable which can be accessed beyond scopes, then this is the variable that you need, but its scope exists only where the class is, and that will be all.
public class GlobalClass {
public static int x = 37;
public static String s = "aaa";
}
This way you can access them with GlobalClass.x
and GlobalClass.s
To define Global Variable you can make use of static Keyword
public final class Tools {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Tools.a;
Tools.b;
Yoy are right...specially in J2ME... You can avoid NullPointerException by putting inside your MidLet constructor (proggy initialization) this line of code:
new Tools();
This ensures that Tools will be allocated before any instruction that uses it.
That's it!
Generally Global variable (I assume you are comparing it with C,Cpp) define as public static final
like
class GlobalConstant{
public static final String CODE = "cd";
}
ENUMs are also useful in such scenario :
For Example Calendar.JANUARY)