Java Reference
In-Depth Information
The class that we write will represent rational numbers. A rational num-
ber stores a numerator and denominator, and we will use
BigIntegers
to repre-
sent the numerator and denominator. Thus our class will be aptly named
BigRational
.
Figure 3.11 shows the
BigRational
class. The online code is fully com-
mented; we have omitted comments in order to allow the code to fit in the text
pages. Lines 5 and 6 are constants
BigRational.ZERO
and
BigRational.ONE
. We
also see that the data representation is two
BigIntegers
,
num
and
den
, and our
code will be implemented in a manner that guarantees that the denominator is
never negative. We provide four constructors, and two of the constructors are
implemented by using the
this
idiom. The other two constructors have more
complicated implementations shown in Figure 3.12. There we see that the
two-parameter
BigRational
constructor initializes the numerator and denomi-
nator as specified, but then must ensure that the denominator is not negative
(which is done by calling private method
fixSigns
) and then reducing out
common factors (which is done by calling private method
reduce
). We also
provide a check to ensure that 0/0 is not accepted as a
BigRational
, and this is
done in
check00
which will throw an exception if there is an attempt to con-
struct such a
BigRational
. The details of
check00
,
fixSigns
, and
reduce
are less
important than the fact that their use in a constructor and other methods
allows the designer of the class to guarantee that objects are always placed in
valid states.
The
BigRational
class also includes methods to return absolute values and
a negative. These are simple and shown in lines 24-27 of Figure 3.11. Note
that these methods return new
BigRational
objects, leaving the original intact.
add
,
subtract
,
multiply
, and
divide
are listed in lines 29-36 of Figure 3.11
and implemented in Figure 3.13. The math is less interesting than a funda-
mental concept that because each of the four routines ends by creating a new
BigRational
, and the
BigRational
constructor has calls to
check00
,
fixSigns
,
and
reduce
, the resulting answers are always in correct reduced form, and an
attempt to do a zero divide by zero would automatically be caught by
check00
.
Finally,
equals
and
toString
are implemented in Figure 3.14. The signa-
ture for
equals
, as discussed earlier, requires a parameter of type
Object
. After
a standard
instanceof
test and type cast, we can compare numerators and
denominators. Notice that we use
equals
(not ==) to compare the numerators
and denominators, and also notice that since
BigRational
s are always in
reduced form, the test is relatively simple. For
toString
, which returns a
String
representation of the
BigRational
, the implementation could be one
line, but we add code to handle infinity and -infinity, and also to not output the
denominator if it is 1.
Search WWH ::
Custom Search