Java Reference
In-Depth Information
Static Variables
A class can have static variables as well as static methods. A static variable is a variable
that belongs to the class as a whole and not just to one object. Each object has its own
copies of the instance variables. However, with a static variable there is only one copy
of the variable, and all the objects can use this one variable. Thus, a static variable can
be used by objects to communicate between the objects. One object can change the
static variable, and another object can read that change. To make a variable static, you
declare it like an instance variable but add the modifier static as follows:
static variable
private static int turn;
Or if you wish to initialize the static variable, which is typical, you might declare it as
follows instead:
private static int turn = 0;
If you do not initialize a static variable, it is automatically initialized to a default
value: Static variables of type boolean are automatically initialized to false . Static
variables of other primitive types are automatically initialized to the zero of their type.
Static variables of a class type are automatically initialized to null , which is a kind of
placeholder for an object that we will discuss later in this chapter. However, we prefer
to explicitly initialize static variables, either as just shown or in a constructor.
Display 5.4 shows an example of a class with a static variable along with a demon-
stration program. Notice that the two objects, lover1 and lover2 , access the same
static variable turn .
As we already noted, you cannot directly access an instance variable within the defini-
tion of a static method. However, it is perfectly legal to access a static variable within a
static method, because a static variable belongs to the class as a whole. This is illustrated
by the method getTurn in Display 5.4. When we write turn in the definition of the
static method getTurn , it does not mean this.turn ; it means TurnTaker.turn . If the
static variable turn were marked public instead of private , it would even be legal to
use TurnTaker.turn outside of the definition of the class TurnTaker .
Defined constants that we have already been using, such as the following, are a spe-
cial kind of static variable:
default
initialization
public static final double PI = 3.14159;
The modifier final in the above means that the static variable PI cannot be changed.
Such defined constants are normally public and can be used outside the class. This
defined constant appears in the class RoundStuff in Display 5.1. To use this constant
outside of the class RoundStuff , you write the constant in the form RoundStuff.PI .
Good programming style dictates that static variables should normally be marked
private unless they are marked final , that is, unless they are defined constants. The
reason is the same as the reason for making instance variables private .
Search WWH ::




Custom Search