Global variables in Java
To define Global Variable you can make use of static Keyword
public class Example {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Example.a;
Example.b;
You don't. That's by design. You shouldn't do it even if you could.
That being said you could create a set of public static members in a class named Globals.
public class Globals {
public static int globalInt = 0;
///
}
but you really shouldn't :). Seriously .. don't do it.
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);
}
}
You are better off using dependency injection:
public class Globals {
public int a;
public int b;
}
public class UsesGlobals {
private final Globals globals;
public UsesGlobals(Globals globals) {
this.globals = globals;
}
}