LISTING 13.13
1 public class Rational extends Number implements Comparable { 2 // Data fields for numerator and denominator 3 private long numerator = 0; 4 private long denominator = 1; 5 6 /** Construct a rational with default properties */ 7 public Rational() { 8 this(0, 1); 9 } 10 11 /** Construct a rational with specified numerator and denominator */ 12 public Rational(long numerator, long denominator) { 13 long gcd = gcd(numerator, denominator); 14 this.numerator = ((denominator > 0) ? 1 : -1) * numerator / gcd; 15 this.denominator = Math.abs(denominator) / gcd; 16 } 17 18 /** Find GCD of two numbers */ 19 private static long gcd(long n, long d) { 20 long n1 = Math.abs(n); 21 long n2 = Math.abs(d); 22 int gcd = 1; 23 24 for (int k = 1; k 0) 111 return 1; 112 else if (this.subtract(o).getNumerator() 13.14 (Demonstrate the benefits of encapsulation) Rewrite the Rational class in Listing 13.13 using a new internal representation for the numerator and denomina- tor. Create an array of two integers as follows: private long]r new long[ 2] Use r[0] to represent the numerator and r[1] to represent the denominator. The signatures of the methods in the Rational class are not changed, so a client application that uses the previous Rational class can continue to use this new Rational class without being recompiled