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?
minutes = (minutes + n) % 1440;
minutes = ((minutes + n) % 1440 + 1440) % 1440;
minutes = Math.abs(minutes + n) % 1440;
if (minutes + n < 1440) { minutes = minutes + n; }
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 ________.
Two hidden representations, one public view
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:
Version B stores two private fields:
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.