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 cal-
culations 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 methods
to the method definition heading, as in the following example:
static
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
were in a class named
, then the following
maximum
SomeClass
is a sample invocation of
:
maximum
int budget = SomeClass.maximum(yourMoney, myMoney);
where
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
and
are variables of type
yourMoney
myMoney
int
in the class
exit
Sys-
is a static method. To end a program immediately, we have used the following
invocation of the static method
tem
:
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
and use it to invoke the
System
method
, but that is confusing style; we usually use the class name when invoking
a static method.)
exit
Search WWH ::




Custom Search