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.
public class Fraction { private int num; private int den; // invariant: den > 0 and gcd(|num|, den) == 1 public Fraction(int n, int d) { if (d == 0) throw new IllegalArgumentException("zero denominator"); if (d < 0) { n = -n; d = -d; } int g = gcd(Math.abs(n), d); num = n / g; den = d / g; } public Fraction times(Fraction other) { return new Fraction(num * other.num, den * other.den); } private static int gcd(int a, int b) { while (b != 0) { int t = a % b; a = b; b = t; } return a; } }
A client runs these three lines:
Fraction a = new Fraction(6, -8); Fraction b = new Fraction(-10, -15); Fraction c = a.times(b);
After these lines run, object a stores numerator and denominator , and object c stores numerator and denominator .
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.
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:
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.