Java Reference
In-Depth Information
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 Programming
Exercise 13.14). 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 13.15).
13.30
Show the output 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());
13.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));
13.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));
13.33
How do you simplify the code in lines 82-85 in Listing 13.13 Rational.java using one
line of code without using the if statement?
13.34
Trace the program carefully and show the output of the following code.
Rational r1 = new Rational( 1 , 2 );
Rational r2 = new Rational( 1 , -2 );
System.out.println(r1.add(r2));
13.10 Class Design Guidelines
Class design guidelines are helpful for designing sound classes.
Key
Point
You have learned how to design classes from the preceding two examples and from many
other examples in the preceding chapters. This section summarizes some of the guidelines.
 
 
 
Search WWH ::




Custom Search