Java Reference
In-Depth Information
Tip
The
get
methods for the properties
numerator
and
denominator
are provided in
the
Rational
class, but the
set
methods are not provided, so, once a
Rational
object is created, its contents cannot be changed. The
Rational
class is immutable.
The
String
class and the wrapper classes for primitive type values are also
immutable.
immutable
Tip
The numerator and denominator are represented using two variables. It is possible to
use an array of two integers to represent the numerator and denominator (see Pro-
gramming Exercise 15.16). The signatures of the public methods in the
Rational
class are not changed, although the internal representation of a rational number is
changed. This is a good example to illustrate the idea that the data fields of a class
should be kept private so as to encapsulate the implementation of the class from the
use of the class.
encapsulation
The
Rational
class has serious limitations and can easily overflow. For example, the fol-
lowing code will display an incorrect result, because the denominator is too large.
overflow
public class
Test {
public static void
main(String[] args) {
Rational r1 =
new
Rational(
1
,
123456789
);
Rational r2 =
new
Rational(
1
,
123456789
);
Rational r3 =
new
Rational(
1
,
123456789
);
System.out.println(
"r1 * r2 * r3 is "
+
r1.multiply(r2.multiply(r3)));
}
}
r1 * r2 * r3 is -1/2204193661661244627
To fix it, you can implement the
Rational
class using the
BigInteger
for numerator and
denominator (see Programming Exercise 15.21).
15.30
Show the printout of the following code?
✓
✓
Check
Point
Rational r1 =
new
Rational(
-2
,
6
);
System.out.println(r1.getNumerator());
System.out.println(r1.getDenominator());
System.out.println(r1.intValue());
System.out.println(r1.doubleValue());
15.31
Why is the following code wrong?
Rational r1 =
new
Rational(
-2
,
6
);
Object r2 =
new
Rational(
1
,
45
);
System.out.println(r2.compareTo(r1));
15.32
Why is the following code wrong?
Object r1 =
new
Rational(
-2
,
6
);
Rational r2 =
new
Rational(
1
,
45
);
System.out.println(r2.compareTo(r1));