| preferred AP College board partner for AP classes
AP Computer Science A/Unit 5: Writing Classes
Start Practice TestPractice Test
Share
About Exam
medium
Rational Class Method Implementation
< Prev
Next >

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;

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy