Two versions of a Timer class have the same public methods but store time differently. Every field starts at 0.
Version A stores one private field:
public class Timer { private int total; // seconds; invariant: total >= 0 public void add(int s) { if (total + s >= 0) total += s; } public int getMinutes() { return total / 60; } public int getSeconds() { return total % 60; } }
Version B stores two private fields:
public class Timer { private int mins; // invariant: mins >= 0 private int secs; // invariant: 0 <= secs <= 59 public void add(int s) { int t = mins * 60 + secs + s; if (t >= 0) { mins = t / 60; secs = t % 60; } } public int getMinutes() { return mins; } public int getSeconds() { return secs; } }
The same client code runs against each version:
Timer t = new Timer(); int[] requests = {150, -200, -90, 75}; for (int s : requests) { t.add(s); System.out.println(t.getMinutes() + ":" + String.format("%02d", t.getSeconds())); }
Complete the table with the value of each private field after each call, and the line the client prints, written as minutes, a colon and two-digit seconds (for example 3:05). Enter whole numbers for the fields.
Unlock full course notes by signing up
Which changes stay hidden from clients
Dozens of other classes use the Java class below, and every one of them uses it only through its public methods.
Which of the following changes can the author make without editing any line of client code and without changing the values clients receive? Select all that apply.
A constructor that normalizes a fraction
The Java class below keeps two private fields and promises that every Fraction object satisfies the invariant written in the comment. Integer division in Java truncates toward zero, and Math.abs returns the absolute value.
A client runs these three lines:
After these lines run, object a stores numerator ________ and denominator ________, and object c stores numerator ________ and denominator ________.
A mutator that preserves a clock invariant
A Java class TimeOfDay stores the time as a private count of minutes since midnight and promises the invariant 0 <= minutes && minutes < 1440. Its method addMinutes(int n) must move the time forward for positive n and backward for negative n, wrapping around midnight. Assume the size of n is under one million, so no overflow occurs. Which body for addMinutes keeps the invariant and produces the correct time for every such n?
Reference leaks through a constructor and a getter
A Java class stores test scores in a private array:
Version A is the class exactly as shown. In Version B, the constructor uses this.scores = scores.clone(); and the getter uses return scores.clone();. In Version C, the constructor is as shown but the getter uses return scores.clone();. The same client code runs against each version:
Give the value printed by g.average() for each version, to one decimal place.