Java Reference
In-Depth Information
83
return true ;
84
else
85
return false ;
86 }
87
88 @Override // Implement the abstract intValue method in Number
89
public int intValue() {
90
return ( int )doubleValue();
91 }
92
93 @Override // Implement the abstract floatValue method in Number
94
public float floatValue() {
95
return ( float )doubleValue();
96 }
97
98 @Override // Implement the doubleValue method in Number
99
public double doubleValue() {
100
return numerator * 1.0 / denominator;
101 }
102
103 @Override // Implement the abstract longValue method in Number
104
public long longValue() {
105
return ( long )doubleValue();
106 }
107
108 @Override // Implement the compareTo method in Comparable
109
public int compareTo(Rational o) {
110
if ( this .subtract(o).getNumerator() > 0 )
111
return 1 ;
112
else if ( this .subtract(o).getNumerator() < 0 )
113
return -1 ;
114
else
115
return 0 ;
116 }
117 }
The rational number is encapsulated in a Rational object. Internally, a rational number is
represented in its lowest terms (line 13), and the numerator determines its sign (line 14). The
denominator is always positive (line 15).
The gcd method (lines 19-30 in the Rational class) is private; it is not intended for use
by clients. The gcd method is only for internal use by the Rational class. The gcd method
is also static, since it is not dependent on any particular Rational object.
The abs(x) method (lines 20-21 in the Rational class) is defined in the Math class and
returns the absolute value of x .
Two Rational objects can interact with each other to perform add, subtract, multiply, and
divide operations. These methods return a new Rational object (lines 43-70).
The methods toString and equals in the Object class are overridden in the Rational
class (lines 72-86). The toString() method returns a string representation of a Rational
object in the form numerator/denominator , or simply numerator if denominator is 1 .
The equals(Object other) method returns true if this rational number is equal to the
other rational number.
The abstract methods intValue , longValue , floatValue , and doubleValue in the
Number class are implemented in the Rational class (lines 88-106). These methods return
the int , long , float , and double value for this rational number.
The compareTo(Rational other) method in the Comparable interface is imple-
mented in the Rational class (lines 108-116) to compare this rational number to the other
rational number.
 
Search WWH ::




Custom Search