AP · Computer Science A · Program Design

Program Design and Abstraction

15 min readUpdated December 1, 2026FreeAP Computer Science A, Class Creation

Program design means planning a class before you code it: list what each object must remember and must do, then write a header for each job. You split large jobs into smaller methods, state what each method assumes and promises, and test the design by tracing calls on chosen inputs. This is how you plan any class in AP® Computer Science A.

Quick check

  1. In the header public int addTwo(int x), what is the return type and what is the parameter?Show answerHide answer

    The return type is int and the parameter is int x: the method receives one int and gives back an int.

  2. A comment above a method says "Precondition: n > 0". Must the method's code check that n is positive?Show answerHide answer

    No. A precondition is a promise made by the calling code, so the method may assume it.

Know these already? Jump to the practice questions

What you'll be able to do

  • Identify the state and behaviors a specification needs.
  • Choose a header that matches each behavior.
  • Explain why helper methods help.
  • Use preconditions and postconditions to judge code.
  • Determine what a sequence of calls prints by tracing.

Key terms

State

The data an object remembers between method calls, held in its instance variables.

In plain English
What the object knows right now.
Don't write
"A local variable is part of the object's state."

Procedural abstraction

Putting a task's steps in a method that other code calls, relying on what it does, not how.

In plain English
Wrap a job in a method once, then just call it.
Don't write
"Abstraction means making variables private."

Precondition

A condition that must be true when a method is called, which the method may assume.

In plain English
The caller's promise.
Don't write
"The method must test its precondition."

Postcondition

What is true when a method ends, if its preconditions held: its return value or how the state changed.

In plain English
The method's promise.
Don't write
"A postcondition is checked before the method runs."

How do you turn a specification into a class?

A specification describes in words what a class must do. Read it twice. First, mark the facts each object must remember between calls: these become private instance variables. Then mark what it must do or answer: each such behavior becomes a method, or the constructor.

A BusPass holds a number of rides, set when bought. Tapping uses a ride if any are left and reports whether the rider may board. Topping up adds rides, and the rider can ask how many are left.

In the specificationBecomes
number of ridesinstance variable ridesLeft
set when boughtconstructor with an int parameter
tappingmethod tap
top-upmethod topUp
how many are leftmethod getRidesLeft

Store only what can't be worked out from other state. A second variable hasRides could fall out of step with ridesLeft; the expression ridesLeft > 0 is always right.

Key idea

Facts the object must remember become instance variables; things it must do or answer become methods.

Check yourself

A Lamp is on or off, and pressing its switch flips it. What instance variable does Lamp need?
Show answerHide answer

One boolean, such as private boolean isOn;, because the lamp must remember which state it is in between presses.

How do you choose each method's header?

A header fixes the return type, the name and the parameters (variables that receive values from the caller). Ask two questions.

  1. What does the caller get back? A behavior that answers a question returns that type; one that only changes the state returns void.
  2. What must the caller supply? Information the object doesn't hold becomes a parameter.
BusPass behaviorHeader
tappublic boolean tap()
top uppublic void topUp(int rides)
rides leftpublic int getRidesLeft()

tap answers "may the rider board?", so it returns a boolean; it needs no parameter because a tap always uses one ride. Methods that other classes call are public and instance variables private, so outside code changes state only through methods.

Examiner's eye

Marks go to headers that match the specification exactly. A method that prints a value it should return does not meet the specification.

Check yourself

A Thermometer must report its reading in degrees as a decimal number. Which header fits?
Show answerHide answer

public double getReading(): it returns a decimal and needs nothing from the caller.

Why split a task into smaller methods?

Splitting a task into methods is procedural abstraction. A helper method does part of another method's job, and the caller relies on the helper's comment, not its code.

/** Precondition: 0 <= n <= 99
 *  Postcondition: returns n as a 2-character String,
 *  with a leading "0" when n < 10
 */
private static String twoDigits(int n)
{
    if (n < 10)
    {
        return "0" + n;
    }
    return "" + n;
}

/** Precondition: 0 <= totalSeconds < 6000
 *  Postcondition: returns the time as "mm:ss"
 */
public static String formatTime(int totalSeconds)
{
    int minutes = totalSeconds / 60;
    int seconds = totalSeconds % 60;
    return twoDigits(minutes) + ":" + twoDigits(seconds);
}

formatTime(125) sets minutes to 2 and seconds to 5, calls the helper twice and returns "02:05". The padding rule is written once, so a fix happens in one place, and each method is short enough to test alone. The helper is private because only its own class uses it.

Check yourself

What does formatTime(59) return?
Show answerHide answer

"00:59". minutes is 0 and seconds is 59.

What do preconditions and postconditions promise?

Together they form a contract, written as a comment above the method.

  • The precondition is the caller's side. twoDigits may assume 0 <= n <= 99, so it has no code to reject 150; a caller who breaks it is promised nothing.
  • The postcondition is the method's side: for every n that meets the precondition, twoDigits returns a 2-character string.

Because formatTime requires totalSeconds < 6000, minutes is at most 99, so both helper calls meet the helper's precondition.

A method is correct when its postcondition holds for every input that meets its precondition, so test the edges of the allowed range: for twoDigits, try 0, 9, 10 and 99.

Check yourself

twoDigits(150) returns "150", 3 characters long. Has twoDigits broken its postcondition?
Show answerHide answer

No. The argument 150 breaks the precondition, so the fault lies with the caller.

Worked example 1: Design a class and test it by tracing

Question: Design a ReadingLog class from this specification, then state what the test code prints. A reading log tracks progress toward a page goal set at creation. The reader can add pages read, ask how many pages are left (never below 0) and ask whether the goal is met.

ReadingLog log = new ReadingLog(100);
log.addPages(30);
log.addPages(45);
System.out.println(log.pagesLeft());
log.addPages(40);
System.out.println(log.pagesLeft());
System.out.println(log.goalMet());

What tells you the method

A specification plus test calls: design the class, then trace the calls.

  1. Step 1: List the state and the behaviors.

    State: int variables goal and pagesRead. Behaviors: a constructor and three methods.

    Why

    Pages left can be worked out from the goal and the running total, so it is not stored.

  2. Step 2: Write the class, reusing one method inside another.

    public class ReadingLog
    {
        private int goal;
        private int pagesRead;
    
        /** Precondition: g > 0 */
        public ReadingLog(int g)
        {
            goal = g;
            pagesRead = 0;
        }
    
        /** Precondition: pages > 0
         *  Postcondition: pagesRead has increased by pages
         */
        public void addPages(int pages)
        {
            pagesRead += pages;
        }
    
        /** Postcondition: returns goal - pagesRead,
         *  or 0 if that would be negative
         */
        public int pagesLeft()
        {
            if (pagesRead >= goal)
            {
                return 0;
            }
            return goal - pagesRead;
        }
    
        public boolean goalMet()
        {
            return pagesLeft() == 0;
        }
    }
    
    Why

    goalMet reuses pagesLeft, so the "never less than 0" rule is written once.

  3. Step 3: Trace the test calls.

    CallgoalpagesReadPrinted
    constructor1000
    addPages(30)10030
    addPages(45)10075
    pagesLeft()1007525
    addPages(40)100115
    pagesLeft()1001150
    goalMet()100115true
    Why

    Only addPages changes the state. Since 115 ≥ 100, pagesLeft returns 0, not −15.

Check it

At the boundary, a goal of 50 with exactly 50 pages read makes 50 >= 50 true, so goalMet() returns true.

Answer

25 then 0 then true

Worked example 2: Choose the code that meets a postcondition

Question: This method is added to the ReadingLog class from Worked example 1. Which code segment can replace /* missing code */?

/** Precondition: perDay > 0
 *  Postcondition: returns the fewest whole days needed
 *  to read the pages left at perDay pages a day
 */
public int daysToFinish(int perDay)
{
    /* missing code */
}
  • A) return pagesLeft() / perDay;
  • B) return (pagesLeft() + perDay - 1) / perDay;
  • C) return pagesLeft() / perDay + 1;
  • D) return (goal + perDay - 1) / perDay;

What tells you the method

"Which code segment" plus a postcondition: test every option on valid inputs.

  1. Step 1: Choose test inputs.

    Let pagesLeft() be 25 (goal 100, 75 read). Then perDay = 10 needs 3 days and perDay = 5 needs exactly 5.

    Why

    int / int truncates, so exact and inexact divisions can behave differently.

  2. Step 2: Trace each option.

    OptionperDay = 10perDay = 5
    A25 / 10 = 225 / 5 = 5
    B34 / 10 = 329 / 5 = 5
    C2 + 1 = 35 + 1 = 6
    D109 / 10 = 10104 / 5 = 20
    Why

    A drops the last part-day, C adds a day to an exact division, and D ignores pages already read.

Check it

When the goal is met, pagesLeft() is 0, so B gives 9 / 10 = 0 days, which is right; C would give 1.

Answer

B

Your turn

Question: Here is the BusPass class written in full. What is printed when the test code runs?

public class BusPass
{
    private int ridesLeft;

    public BusPass(int rides)
    {
        ridesLeft = rides;
    }

    public boolean tap()
    {
        if (ridesLeft > 0)
        {
            ridesLeft--;
            return true;
        }
        return false;
    }

    public void topUp(int rides)
    {
        ridesLeft += rides;
    }

    public int getRidesLeft()
    {
        return ridesLeft;
    }
}
BusPass p = new BusPass(2);
p.tap();
p.tap();
System.out.println(p.tap());
p.topUp(5);
p.tap();
System.out.println(p.getRidesLeft());
  1. Step 1: Trace the first two taps.

    ridesLeft starts at 2, and each tap finds ridesLeft > 0 and subtracts 1, so it ends at 0. Nothing is printed yet.

  2. Step 2: Your go: trace the third tap, the top-up and the last tap, then write both printed lines.

Show the full solutionHide the solution

Step 2. The third tap finds 0 > 0 false, so ridesLeft stays 0 and tap returns false, which is printed. topUp(5) makes ridesLeft 5, the last tap makes it 4, and getRidesLeft() returns 4, which is printed.

Answer: false then 4 on the next line.

Traps

Trap

A method must test its own precondition and reject bad input.

It seems right because extra checks look safer. But a precondition is the caller's promise, so the method may assume it and needs no checking code.

A method's precondition is amount > 0. Does its code need an if statement that rejects amount <= 0?

No. Making amount > 0 true is the caller's job.

Trap

Printing a value does the same job as returning it.

It seems right because both show the value in a test. But "returns" means the caller gets the value back to use; printing gives the caller nothing.

A specification says getTotal returns the int total. Does a void getTotal method that prints total meet it?

No. It needs the header public int getTotal() and the statement return total;.

What's examined

On the AP® Computer Science A exam, program design belongs to Unit 3 (Class Creation). Multiple-choice questions can ask which header or code segment fits a specification, or what a sequence of calls prints. One of the four free-response questions is a class design question: you write a whole class from a specification, judged on whether it does what the specification says, with the names and headers given.

Practice questions

  1. Recall Which statement describes a precondition?
  • A) A condition the caller must make true before calling the method
  • B) A condition the method guarantees is true when it returns
  • C) A condition the method must test, printing an error if it fails
  • D) A condition that must hold for the class to compile
Show answer

Answer: A. A precondition is the caller's side of the contract.

Why the others are wrong:

  • B describes a postcondition, the method's side of the contract.
  • C treats the precondition as something the method checks, when the method may simply assume it.
  • D confuses a precondition with Java's syntax rules; code that breaks a precondition still compiles.
  1. Apply A Thermostat remembers a target temperature, a whole number of degrees that starts at 20. Pressing up or down changes the target by 1, and the thermostat can report its target. Which instance variable declaration fits this design?
  • A) private boolean up;
  • B) public int target;
  • C) private int target;
  • D) private String target;
Show answer

Answer: C. The one fact the thermostat must remember is a whole number, so it needs a private int.

Why the others are wrong:

  • A turns a behavior, pressing up, into state; pressing is a method, not something remembered.
  • B makes the state public, so outside code could change the target without using the methods.
  • D stores a number as text, so the methods could not add 1 to it.
  1. Apply What is printed when the code after this class runs?
public class Score
{
    private int points;
    private int streak;

    public Score()
    {
        points = 0;
        streak = 0;
    }

    public void hit()
    {
        streak++;
        points += bonus();
    }

    public void miss()
    {
        streak = 0;
    }

    private int bonus()
    {
        return streak * 10;
    }

    public int getPoints()
    {
        return points;
    }
}
Score s = new Score();
s.hit();
s.hit();
s.miss();
s.hit();
System.out.println(s.getPoints());
Show answer

Answer: 40

Marking points:

  • First hit: streak becomes 1, then bonus() returns 10, so points is 10.
  • Second hit: streak is 2 and points is 10 + 20 = 30.
  • miss sets streak to 0; the last hit makes streak 1 and points 40.
  1. Apply What value does the expression score(37) + score(60) have?
public static int clamp(int value, int low, int high)
{
    if (value < low)
    {
        return low;
    }
    if (value > high)
    {
        return high;
    }
    return value;
}

public static int score(int raw)
{
    return clamp(raw * 2, 0, 100) / 10;
}
Show answer

Answer: 17

Marking points:

  • score(37): clamp(74, 0, 100) returns 74, and 74 / 10 is 7 in integer division.
  • score(60): clamp(120, 0, 100) returns 100, and 100 / 10 is 10.
  • 7 + 10 = 17.
  1. Exam-style In a Battery class, charge is a private int instance variable. The method below has the precondition amount > 0 and this postcondition: if charge is at least amount, charge decreases by amount and the method returns true; otherwise charge is unchanged and it returns false. Give the number of the line that stops the method meeting its postcondition.
1: public boolean use(int amount)
2: {
3:     if (charge > amount)
4:     {
5:         charge -= amount;
6:         return true;
7:     }
8:     return false;
9: }
Show answer

Answer: Line 3.

Marking points:

  • When charge and amount are both 30, the postcondition says the method should use the charge and return true, but 30 > 30 is false, so it returns false.
  • Changing line 3 to if (charge >= amount) fixes it: charge becomes 0 and the method returns true.
  1. Exam-style The method clockTime must use the helper twoDigits. Which code segment can replace /* missing code */?
/** Precondition: 0 <= n <= 99
 *  Postcondition: returns n as a 2-character String
 */
private static String twoDigits(int n)
{
    if (n < 10)
    {
        return "0" + n;
    }
    return "" + n;
}

/** Precondition: 0 <= mins < 1440
 *  Postcondition: returns the time as "hh:mm";
 *  for example, 75 gives "01:15"
 */
public static String clockTime(int mins)
{
    /* missing code */
}
  • A) return mins / 60 + ":" + mins % 60;
  • B) return twoDigits(mins % 60) + ":" + twoDigits(mins / 60);
  • C) return twoDigits(mins / 60) + ":" + twoDigits(mins);
  • D) return twoDigits(mins / 60) + ":" + twoDigits(mins % 60);
Show answer

Answer: D. For 75 it returns twoDigits(1) + ":" + twoDigits(15), which is "01:15".

Why the others are wrong:

  • A skips the helper, so 75 gives "1:15" with no leading zero.
  • B swaps hours and minutes, so 75 gives "15:01".
  • C passes all the minutes instead of the remainder, so 75 gives "01:75"; any mins above 99 also breaks the helper's precondition.

Key points

Recall, then reveal

Say the main points from memory first, then check them.

Show key pointsHide key points
  • Facts an object must remember become private instance variables; jobs it must do or answer become methods.
  • Don't store a value you can compute from other state: compute it when asked.
  • The return type comes from what the caller gets back (void if nothing); the parameters come from what the caller must supply.
  • Helper methods hold one task each, so a rule is written once and each piece can be tested alone.
  • A precondition is the caller's promise; a postcondition is the method's promise for every input that meets the precondition.
  • Test a design by tracing calls on stated inputs, including values at the edges of the allowed range.

Keep learning

Prerequisites: Writing Methods

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Class Creation

All Program Design notes

Part of Novark's AP Computer Science A notes