Java Reference
In-Depth Information
Remember that in Java, class methods are declared with the
static
keyword, and the terms static method and class
method are used interchangeably.
For example, when working with the
Circle
class you might find that you often
want to compute the area of a circle with a given radius but don't want to bother
creating a
Circle
object to represent that circle. In this case, a class method is more
convenient:
public
static
double
area
(
double
r
)
{
return
PI
*
r
*
r
;
}
It is perfectly legal for a class to define more than one method with the same name,
as long as the methods have different parameters. This version of the
area()
method is a class method, so it does not have an implicit
this
parameter and must
have a parameter that specifies the radius of the circle. This parameter keeps it dis‐
tinct from the instance method of the same name.
As another example of the choice between instance methods and class methods,
consider defining a method named
bigger()
that examines two
Circle
objects and
returns whichever has the larger radius. We can write
bigger()
as an instance
method as follows:
// Compare the implicit "this" circle to the "that" circle passed
// explicitly as an argument and return the bigger one.
public
Circle
bigger
(
Circle
that
)
{
if
(
this
.
r
>
that
.
r
)
return
this
;
else
return
that
;
}
We can also implement
bigger()
as a class method as follows:
// Compare circles a and b and return the one with the larger radius
public
static
Circle
bigger
(
Circle
a
,
Circle
b
)
{
if
(
a
.
r
>
b
.
r
)
return
a
;
else
return
b
;
}
Given two
Circle
objects,
x
and
y
, we can use either the instance method or the
class method to determine which is bigger. The invocation syntax differs signifi‐
cantly for the two methods, however:
// Instance method: also y.bigger(x)
Circle
biggest
=
x
.
bigger
(
y
);
Circle
biggest
=
Circle
.
bigger
(
x
,
y
);
// Static method
Both methods work well, and, from an object-oriented design standpoint, neither of
these methods is “more correct” than the other. The instance method is more for‐
mally object oriented, but its invocation syntax suffers from a kind of asymmetry. In
a case like this, the choice between an instance method and a class method is simply