Java Reference
In-Depth Information
tianCount
to be
static
, making
martianCount
classwide data. Every
Martian
can see the
martianCount
as if it were an instance variable of class
Martian
, but only
one
copy of the
static
martianCount
is maintained. This saves space. We save time by having the
Mar-
tian
constructor increment the
static
martianCount
—there's only one copy, so we do
not have to increment separate copies for each
Martian
object.
Software Engineering Observation 8.9
Use a
static
variable when all objects of a class must use the same copy of the variable.
Class Scope
Static variables have
class scope
—they can be used in all of the class's methods. We can ac-
cess a class's
public
static
members through a reference to any object of the class, or by
qualifying the member name with the class name and a dot (
.
), as in
Math.random()
. A
class's
private
static
class members can be accessed by client code only through methods
of the class. Actually,
static
class members exist even when no objects of the class exist
—
they're available as soon as the class is loaded into memory at execution time. To access a
public
static
member when no objects of the class exist (and even when they do), prefix
the class name and a dot (
.
) to the
static
member, as in
Math.PI
. To access a
private
static
member when no objects of the class exist, provide a
public
static
method and
call it by qualifying its name with the class name and a dot.
Software Engineering Observation 8.10
Static class variables and methods exist, and can be used, even if no objects of that class
have been instantiated.
static
Methods Cannot Directly Access Instance Variables and Instance Methods
A
static
method
cannot
access a class's instance variables and instance methods, because
a
static
method can be called even when no objects of the class have been instantiated.
For the same reason, the
this
reference
cannot
be used in a
static
method. The
this
ref-
erence must refer to a specific object of the class, and when a
static
method is called, there
might not be any objects of its class in memory.
Common Programming Error 8.5
A compilation error occurs if a
static
method calls an instance method in the same class
by using only the method name. Similarly, a compilation error occurs if a
static
method
attempts to access an instance variable in the same class by using only the variable name.
Common Programming Error 8.6
Referring to
this
in a
static
method is a compilation error.
Tracking the Number of Employee Objects That Have Been Created
Our next program declares two classes—
Employee
(Fig. 8.12) and
EmployeeTest
(Fig. 8.13). Class
Employee
declares
private
static
variable
count
(Fig. 8.12, line 7) and
public
static
method
getCount
(lines 36-39). The
static
variable
count
maintains a
count of the number of objects of class
Employee
that have been created so far. This class