Trace a mutator that delegates to a status-returning setter

A parking meter class stores the minutes remaining and counts rejected requests:


Java
public class ParkingMeter {
    private int minutes = 30;
    private int rejected = 0;

    public int getMinutes() { return minutes; }
    public int getRejected() { return rejected; }

    public boolean setMinutes(int newMinutes) {
        if (newMinutes < 0 || newMinutes > 120) {
            rejected++;
            return false;
        }
        minutes = newMinutes;
        return true;
    }

    public void addMinutes(int extra) {
        if (!setMinutes(minutes + extra)) {
            setMinutes(120);
        }
    }
}


A client runs these statements in order:


Java
ParkingMeter m = new ParkingMeter();
m.addMinutes(45);                        // statement 1
m.setMinutes(-10);                       // statement 2
m.addMinutes(60);                        // statement 3
boolean ok = m.setMinutes(m.getMinutes() - 50); // statement 4
m.addMinutes(m.getMinutes());            // statement 5


Find the value of minutes right after statement 4, the final value of minutes, the final value of rejected, and the value stored in ok. Give the three counts as whole numbers and ok as true or false.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Accessors and Mutators Questions: