Question:
One of the things left out of Java that we had in C++ was
global variables. Is there a way to use global variables in Java?
Answer:
Even though Java requires that all variables and functions must be
declared within the scope of a class, it is possible to have global
variables. Think of System.in and System.out for example. They are global
variables accessible to all parts of an application. You can
implement global variables in a Java application by declaring them as
static members of a class. For an application it will sometimes make
sense to declare an ApplicationGlobals class that only contains
public static variables and methods intended for use throughout the entire
application.
More often than not, however, the aggregation of globals
into a single class can be avoided. As your application evolves, you
will often find that global variables are a source of problems when
adding new functionality. It is often possible to provide globally
accessible instances of objects through default factory methods, such
as java.awt.Toolkit.getDefaultToolkit(). It can also be a good idea
to use synchronized set and get methods to access the global data in
order to avoid potential conflicts between threads modifying public
variables.