09 RationalClass
09 RationalClass
Java
An Introduction
ERIC S. ROBERTS to Computer Science
CHAPTER 6
Subtraction: Division:
a c ad – bc a .. c ad
– = =
b d bd b d bc
Implementing the Rational Class
• The next five slides show the code for the Rational class
along with some brief annotations.
• As you read through the code, the following features are
worth special attention:
– The constructors for the class are overloaded. Calling the constructor
with no argument creates a Rational initialized to 0, calling it with
one argument creates a Rational equal to that integer, and calling it
with two arguments creates a fraction.
– The constructor makes sure that the numerator and denominator of any
Rational are always reduced to lowest terms. Moreover, since these
values never change once a new Rational is created, this property
will remain in force.
– The add, subtract, multiply, and divide methods are written so
that one of the operands is the receiver (signified by the keyword
this) and the other is passed as an argument. Thus to add r1 and r2
you would write:
r1.add(r2)
The Rational Class
/**
* The Rational class is used to represent rational numbers, which
* are defined to be the quotient of two integers.
*/ As always, the instance variables are private to this class.
public class Rational {
/* Private instance variables */
private int num; /* The numerator of this Rational */
private int den; /* The denominator of this Rational */
TestRational
1/2 + 1/3 + 1/6 = 1
skip simulation