Java Reference
In-Depth Information
5.1
Static Methods and Static Variables
All for one, one for all, that is our device.
ALEXANDRE DUMAS,
The Three Musketeers
Static Methods
Some methods do not require a calling object. Methods to perform simple numeric
calculations are good examples. For example, a method to compute the maximum of two
integers has no obvious candidate for a calling object. In Java, you can define a method
so that it requires no calling object. Such methods are known as
static methods
. You
define a static method in the same way as any other method, but you add the keyword
static
to the method definition heading, as in the following example:
static
methods
public static int
maximum(
int
n1,
int
n2)
{
if
(n1 > n2)
return
n1;
else
return
n2;
}
Although a static method requires no calling object, it still belongs to some class,
and its definition is given inside the class definition. When you invoke a static method,
you normally use the class name in place of a calling object. So if the above definition
of the method
maximum
were in a class named
SomeClass
, then the following is a
sample invocation of
maximum
:
int
budget = SomeClass.maximum(yourMoney, myMoney);
where
yourMoney
and
myMoney
are variables of type
int
that contain some values.
A sample of some static method definitions, as well as a program that uses the
methods, are given in Display 5.1 .
We have already been using one static method. The method
exit
in the class
System
is a static method. To end a program immediately, we have used the following
invocation of the static method
exit
:
System.exit(0);
Note that with a static method, the class name serves the same purpose as a calling
object. (It would be legal to create an object of the class
System
and use it to invoke the
method
exit
, but that is confusing style; we usually use the class name when invoking
a static method.)