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:


Java
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:


Java
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:


Java
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.

CallVersion A totalVersion B minsVersion B secsClient display (m:ss)
add(150)
add(-200)
add(-90)
add(75)

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 Encapsulation and Information Hiding Questions: