Rational Class Method Implementation
Consider the following Rational class and the implementation of its plus method.
public class Rational
{
private int numerator;
private int denominator;
/** default constructor */
Rational()
{ /* implementation not shown */ }
/** Constructs a Rational with numerator n and
* denominator 1. */
Rational(int n)
{ /* implementation not shown */ }
/** Constructs a Rational with specified numerator and
* denominator. */
Rational(int numer, int denom)
{ /* implementation not shown */ }
/** Returns numerator. */
int numerator()
{ /* implementation not shown */ }
/** Returns denominator. */
int denominator()
{ /* implementation not shown */ }
/** Returns (this + r). Leaves this unchanged.
*/
public Rational plus(Rational r)
{ /* implementation not shown */ }
// Similarly for times, minus, divide
...
/** Ensures denominator > 0. */
private void fixSigns()
{ /* implementation not shown */ }
/** Ensures lowest terms. */
private void reduce()
{ /* implementation not shown */ }
}
The implementation of the plus method is shown below.
/** Returns (this + r). Leaves this unchanged. */
public Rational plus(Rational r) {
fixSigns();
r.fixSigns();
int denom = denominator * r.denominator;
int numer = numerator * r.denominator + r.numerator * denominator;
/* more code */
}
Which of the following code segments should replace /* more code */ for the plus method to function correctly?
A
reduce();
Rational rat = new Rational(numer, denom);
return rat;
B
return new Rational(numer, denom);
C
Rational rat = new Rational(numer, denom);
rat.reduce();
return rat;
D
Rational rat = new Rational(numer, denom);
Rational.reduce();
return rat;
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE