Java Reference
In-Depth Information
Type
Initial Value
byte, short, int, long
0
float, double
+0.0
object reference
null
2.2.2. Static Fields
Sometimes you want only one instance of a field shared by all objects
of a class. You create such fields by declaring them
static
, so they are
called
static fields
or
class variables.
When you declare a
static
field in
a class only one copy of the field exists, no matter how many instances
of the class are created.
In our case,
Body
has one
static
field,
nextID
, which contains the next
body identifier to use. The
nextID
field is initialized to zero when the class
is initialized after it is loaded (see "
Loading Classes
" on page
435
). You
will see that each newly created
Body
object will be assigned the current
value of
nextID
as its identifier, and the value of
nextID
will be incremen-
ted. Hence, we only want one copy of the
nextID
field, to be used when
creating all
Body
instances.
Within its own class a
static
field can be referred to directly, but when
accessed externally it must usually be accessed using the class name.
For example, we could print the value of
nextID
as follows:
System.out.println(Body.nextID);