AP Computer Science A · Unit 3 lecture · Part 10 of 10 · 12 min

Unit 3 wrap-upPut it together

Mr. Thompkins
You can now build a class from nothing. Let's zoom out, collect the keywords in one place, and then write a full Class Design FRQ the way the exam grades it.
WordWhat it meansWhere you use it
publicAny class can use itThe class, its constructors, methods clients call
privateOnly code inside this class can use itEvery instance variable; helper methods
staticBelongs to the class: one shared copyCounters, constants, utility methods
finalCan be assigned only onceConstants such as MAX_ITEMS
voidReturns nothingMethods that only change state or print
returnEnds the method and sends a value backEvery path of a non-void method
newBuilds an object and runs a constructorClient code, and constructors that copy
thisThe object whose method is runningthis.x = x; passing or returning the current object
The words of Unit 3 on one page.

Three threads run through the whole unit. First, the author protects the object: private data, constructors that set everything, mutators that keep values valid. Second, references: an object variable is an arrow, so assignments and parameters make aliases, and only new makes a new object. Third, every name has a home: instance, static, parameter or local, and the home decides where it can be used and how long it lives.

?Wait, accessor or mutator: which is which?
An accessor returns information and changes nothing, like getCharge(). A mutator changes instance variables, like recharge(90). A method can be both, like use(25), which changes the charge and returns whether it worked.
Pause and think
Connect two sections: why is it a problem if a constructor stores a mutable object it was given, and how is that the same idea as aliasing in 3.6?
I thought about it. Show me
Storing the parameter's reference makes the instance variable an alias of the caller's object. Then any change the caller makes later reaches inside your object, and your private data is no longer private in practice. Storing a copy, made with new, breaks the alias.

The Class Design FRQ

Question 2 on the exam is always Class Design, worth 7 points. You get a description of a class and a table of example calls with their results, and you write the entire class: header, instance variables, constructor and methods. No starter code. The table is the specification, so read it row by row before you write anything.

StatementReturnsExplanation
ParkingMeter m = new ParkingMeter(120);holds at most 120 minutes; starts at 0
m.isExpired()trueno time on the meter
m.addQuarters(5)755 quarters is 75 minutes
m.passTime(30);45 minutes left
m.isExpired()false
m.addQuarters(6)7545 + 90 = 135, capped at 120: 75 added
m.passTime(200);time never goes below 0
m.isExpired()true
The specification for ParkingMeter, as the exam would give it. The highlighted row is the hard one.
Write the whole class
A ParkingMeter is built with the most minutes it can hold, and it starts with no time. addQuarters(q) adds 15 minutes per quarter, but the time never goes above the maximum; it returns how many minutes were actually added. passTime(minutes) uses up time, never going below 0. isExpired() returns true when no time is left. Write the complete ParkingMeter class, using the table above.
1public class ParkingMeter12{3    private int maxMinutes;24    private int minutesLeft;256    public ParkingMeter(int maxMinutes)37    {8        this.maxMinutes = maxMinutes;39        minutesLeft = 0;310    }1112    public int addQuarters(int q)413    {14        int before = minutesLeft;515        minutesLeft += 15 * q;516        if (minutesLeft > maxMinutes)517        {518            minutesLeft = maxMinutes;519        }520        return minutesLeft - before;521    }2223    public void passTime(int minutes)424    {25        minutesLeft -= minutes;626        if (minutesLeft < 0)627        {628            minutesLeft = 0;629        }630    }3132    public boolean isExpired()433    {34        return minutesLeft == 0;735    }36}
  1. line 1 Point 1: public class header
  2. line 3-4 Point 2: private instance variables for what must be remembered
  3. line 6-9 Point 3: constructor sets every instance variable
  4. line 12-32 Point 4: public method headers with the right return types
  5. line 14-20 Point 5: add, cap, and return what was really added
  6. line 25-29 Point 6: subtract, never below 0
  7. line 34 Point 7: the boolean answer, from the state
  1. Header: public class ParkingMeter.
    Why?
    Point 1 is often just the header. Spell the name exactly as the problem does.
  2. What must it remember between calls? The maximum and the minutes left. private int maxMinutes; private int minutesLeft;
    Why?
    Point 2. The number of quarters doesn't need to be stored: it's used once, inside addQuarters.
  3. Constructor: public ParkingMeter(int maxMinutes) { this.maxMinutes = maxMinutes; minutesLeft = 0; }
    Why?
    Point 3 checks that every instance variable is set, including the one with no parameter.
  4. Headers from the table: addQuarters returns a number, so public int addQuarters(int q). passTime returns nothing, so public void passTime(int minutes). isExpired returns true or false, so public boolean isExpired().
  5. addQuarters: remember the old time, add 15 * q, cap at maxMinutes, and return the new time minus the old.
    Why?
    The highlighted row: 45 + 90 = 135 is capped to 120, so only 75 minutes were added. Returning 15 * q (90) is the most common lost point.
  6. passTime: subtract, then if minutesLeft < 0, set it to 0.
  7. isExpired: return minutesLeft == 0;
    Why?
    Return the boolean expression itself. No if needed.

Answer: See the complete class below. Running the table's calls prints true, 75, false, 75, true.

Stuck? Get a hint
  1. List what the meter must remember, then turn each table row into a method header.
  2. For addQuarters, save the old minutes before you change anything.
  3. The amount added is the new time minus the old time, after the cap.

Traps that cost points

✕ Writing size = size; in a constructor whose parameter is also size.
✓ Write this.size = size;. Without this, the instance variable keeps its default.
✕ Writing int total = 0; or String code = c; for an instance variable inside a method or constructor.
✓ No type in front of an instance variable once it's declared. The type creates a new local variable.
✕ Giving a constructor a return type, like public void Meter().
✓ Constructors have no return type at all. With void, it's an ordinary method.
✕ Making instance variables public.
✓ Always private. That's a rubric point.
✕ Using an instance variable inside a static method.
✓ Static methods have no object. Use parameters or static variables there.
✕ Thinking a method can change an int argument back in the caller.
✓ Primitive parameters are copies. Return the new value instead.
✕ Thinking t = new Tank(...) inside a method changes the caller's object.
✓ It only re-aims the parameter. Calling a mutator through the parameter is what changes the object.
✕ Leaving a path with no return in a non-void method.
✓ End with an else or a final return so every path returns.
✕ Printing a result when the method should return it.
✓ "Returns" means a return statement.

Unit 3 code patterns

private int minutesLeft;
Instance variableOne per object, always private
private static int placed = 0;
Class variableOne shared copy: counters
public static final int MAX = 5;
Class constantShared and never reassigned
public Meter(int max) { this.max = max; }
ConstructorClass name, no return type; this.max is the instance variable
public int getMax() { return max; }
AccessorReturns data, changes nothing
public void reset() { minutesLeft = 0; }
MutatorChanges state
bed = new Plot(p.getWidth(), p.getLength());
Copy a mutable parameterAvoids an alias to the caller's object
c.addMember(this); return this;
thisPass or return the current object
Order.isValid(7)
Calling a class methodOn the class name, no object needed

FRQ strategy for Class Design

  1. Read the description and the whole example table first. Circle every value the object must remember from one call to the next: those are your instance variables.
  2. Write the class header and the private instance variables before anything else. They're quick points.
  3. Write the constructor next and set every instance variable, from a parameter or a fixed starting value.
  4. Turn each different method in the table into a header. Pick the return type from what the call gives back: a number, a String, true or false, or nothing.
  5. Write each method body, then check it against every table row, especially the strange ones: caps, resets, ties and empty cases.
  6. Return what the problem says to return, on every path. Don't print unless it says print.
  7. Use the problem's exact names. A misspelled method name can cost the point for that method.
Check yourself
Using the ParkingMeter class above, what is printed?
ParkingMeter m = new ParkingMeter(60);
m.addQuarters(3);
m.passTime(10);
System.out.println(m.addQuarters(2));
  1. A25
  2. B30
  3. C60
  4. D20
Show the answer

A. 3 quarters add 45 minutes (45 left). passTime(10) leaves 35. Two quarters would make 65, which is capped at 60, so only 25 minutes were added. The second choice is the top trap: 15 * 2 = 30 ignores the cap.

Check yourself
A Song class has private instance variables title (String) and length (int). Which constructor body correctly sets both from the parameters of public Song(String title, int seconds)?
  1. Atitle = title; length = seconds;
  2. Bthis.title = title; length = seconds;
  3. Cthis.title = title; int length = seconds;
  4. Dtitle = this.title; this.length = seconds;
Show the answer

B. The parameter title hides the instance variable, so you need this.title = title. length has no name clash, so length = seconds works. The first choice assigns the parameter to itself, the third creates a local length, and the fourth copies the instance variable's default (null) into the parameter, which is backwards.

Mr. Thompkins
That's Unit 3. Now go practice while it's fresh: take the Unit 3 quiz, and try a Class Design FRQ from the practice set with a timer. When something trips you up, come back to that section and open its recall cards. See you in Unit 4, where one object can hold a whole list of others.