Dozens of other classes use the Java class below, and every one of them uses it only through its public methods.
public class Rectangle { private double width; // metres private double height; // metres public double getWidth() { return width; } public void setWidth(double w) { if (w > 0) width = w; } public double getHeight() { return height; } public void setHeight(double h) { if (h > 0) height = h; } public double getArea() { return width * height; } }
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.
Make width and height public and delete the four getter and setter methods, since clients could then use the fields directly.
Add a private field that caches the area, update it inside both setters, and have getArea return the cached value.
Rename the public method getArea to area so that it matches the naming style of a newer library.
Rename the private field width to widthM and update every line inside the class that refers to it.
Replace the two fields with one private double[] of length 2, holding width at index 0 and height at index 1, and update the method bodies.
Unlock full course notes by signing up
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:
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.