Java Reference
In-Depth Information
Deciding whether to declare a method or variable as static is a key step in class
design. Let's examine the implications of static variables and methods more closely.
Static Variables
So far, we've seen two categories of variables: local variables that are declared
inside a method, and instance variables that are declared in a class but not inside
a method. The term
instance variable
is used, because each instance
of the class has its own version of the variable. That is, each object
has distinct memory space for each variable so that each object can
have a distinct value for that variable.
A
static variable,
which is sometimes called a
class variable
, is
shared among all instances of a class. There is only one copy of a static variable
for all objects of the class. Therefore, changing the value of a static variable in
one object changes it for all of the others. The reserved word
static
is used as a
modifier to declare a static variable as follows:
KEY CONCEPT
A static variable is shared among all
instances of a class.
private static int
count = 0;
Memory space for a static variable is established when the class that contains
it is referenced for the first time in a program. A local variable declared within a
method cannot be static.
Constants, which are declared using the
final
modifier, are often declared
using the
static
modifier. Because the value of constants cannot be changed,
there might as well be only one copy of the value across all objects of the class.
Static Methods
In Chapter 3 we briefly introduced the concept of a
static method
(also called a
class method
). Static methods can be invoked through the class name. We don't
have to instantiate an object of the class in order to invoke the method. In Chapter 3
we noted that all the methods of the
Math
class are static methods. For example, in
the following line of code the
sqrt
method is invoked through the
Math
class name:
System.out.println ("Square root of 27: " + Math.sqrt(27));
The methods in the
Math
class perform basic computations based on values
passed as parameters. There is no object state to maintain in these situations; there-
fore, there is no good reason to create an object in order to request these services.
A method is made static by using the
static
modifier in the method declara-
tion. As we've seen many times, the
main
method of a Java program must be
declared with the
static
modifier; this is done so that
main
can be executed by
the interpreter without instantiating an object from the class that contains
main
.
Search WWH ::
Custom Search