Java Reference
In-Depth Information
Rational r1 =
new
Rational(
4
,
2
);
5
6
7
8
// Display results
9 System.out.println(r1 +
" + "
+ r2 +
" = "
+
create a
Rational
create a
Rational
Rational r2 =
new
Rational(
2
,
3
);
r1.add(r2)
add
);
10 System.out.println(r1 +
" - "
+ r2 +
" = "
+
r1.subtract(r2)
);
r1.multiply(r2)
11 System.out.println(r1 +
" * "
+ r2 +
" = "
+
);
12 System.out.println(r1 +
" / "
+ r2 +
" = "
+
r1.divide(r2)
);
r2.doubleValue()
13 System.out.println(r2 +
" is "
+
);
14 }
15 }
2 + 2/3 = 8/3
2 - 2/3 = 4/3
2 * 2/3 = 4/3
2 / 2/3 = 3
2/3 is 0.6666666666666666
The
main
method creates two rational numbers,
r1
and
r2
(lines 5-6), and displays the
results of
r1 + r2
,
r1 - r2
,
r1 x r2
, and
r1 / r2
(lines 9-12). To perform
r1 + r2
,
invoke
r1.add(r2)
to return a new
Rational
object. Similarly, invoke
r1.subtract(r2)
for
r1 - r2
,
r1.multiply(r2)
for
r1 x r2
, and
r1.divide(r2)
for
r1 / r2
.
The
doubleValue()
method displays the double value of
r2
(line 13).
The double-
Value()
method is defined in
java.lang.Number
and overridden in
Rational
.
Note that when a string is concatenated with an object using the plus sign (
+
), the object's
string representation from the
toString()
method is used to concatenate with the string. So
r1 + " + " + r2 + " = " + r1.add(r2)
is equivalent to
r1.toString() + " + "
+ r2.toString() + " = " + r1.add(r2).toString()
.
The
Rational
class is implemented in Listing 15.13.
L
ISTING
15.13
Rational.java
1
public class
Rational
extends
Number
implements
Comparable<Rational>
{
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
;