Java Reference
In-Depth Information
LISTING 7.4
continued
}
//-----------------------------------------------------------------
// Computes and returns the greatest common divisor of the two
// positive parameters. Uses Euclid's algorithm.
//-----------------------------------------------------------------
private int
gcd (
int
num1,
int
num2)
{
while
(num1 != num2)
if
(num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
return
num1;
}
}
The methods of the
RationalNumber
class, such as
add
,
subtract
,
multiply
,
and
divide
, use the
RationalNumber
object that is executing the method as the
first (left) operand and the
RationalNumber
object passed as a parameter as the
second (right) operand.
The
isLike
method of the
RationalNumber
class is used to determine if two
rational numbers are essentially equal. It's tempting, therefore, to call that method
equals
, similar to the method used to compare
String
objects (discussed in
Chapter 5). However, in Chapter 9 we will discuss how the
equals
method is
somewhat special due to inheritance, and that it should be implemented in a par-
ticular way. So to avoid confusion we call this method
isLike
for now.
Note that some of the methods in the
RationalNumber
class, including
reduce
and
gcd
, are declared with private visibility. These methods are
private
because
we don't want them executed directly from outside a
RationalNumber
object.
They exist only to support the other services of the object.
Aggregation
Some objects are made up of other objects. A car, for instance, is made up of its
engine, its chassis, its wheels, and several other parts. Each of these
other parts could be considered a separate object. Therefore we can
say that a car is an
aggregation
—it is composed, at least in part, of
other objects. Aggregation is sometimes described as a
has-a rela-
tionship.
For instance, a car has a chassis.
KEY CONCEPT
An aggregate object is composed
of other objects, forming a has-a
relationship.
Search WWH ::
Custom Search