Skip to content

Course navigation

For teachersTopic 3.3 · Lesson kit

Anatomy of a Class

  • 2 class periods
  • 45 minutes each
  • Objective 3.3.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    2 periods of 45 minutes

  • Worksheet

    Puzzles, about 30 minutes

  • Worksheet key

    Answer key

  • Exit ticket

    End of the last period

  • Exit ticket key

    Answer key

Download all AP CSA teacher filesEvery topic's slides, lesson plan, worksheet, and exit ticket, with keys (.zip)

At a glance

Pacing
2 class periods of 45 minutes
Learning objectives
3.3.A
Essential knowledge
3.3.A.13.3.A.23.3.A.33.3.A.43.3.A.53.3.A.6
Materials
Projector and the Inside the Class slide deckWhiteboard and markersMini whiteboards or scrap paperIDE on the projector (students' IDEs optional)Printed Inside the Class puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upwhat can you reach? (slides 2–3)
  2. 0:05–0:2015 minDirect instructionthe parts of a class, constructor or method (slides 4–6)
  3. 0:20–0:3212 minDirect instructionevery object has its own copy (slides 7–8)
  4. 0:32–0:408 minGuided practicewhose cookies? (slide 9) and worksheet question 1
  5. 0:40–0:455 minClosurecount the copies

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Activity
  1. 0:00–0:044 minWarm-upcheck worksheet question 2
  2. 0:04–0:1410 minDirect instructionpublic and private (slides 10–13)
  3. 0:14–0:206 minGuided practicewhich lines compile? (slide 14)
  4. 0:20–0:288 minDirect instructionencapsulation (slides 15–16)
  5. 0:28–0:357 minDirect instructionaccess for classes, constructors, and methods (slide 17)
  6. 0:35–0:4510 minActivityDay 2 closure (slides 18–19) and exit ticket

Overview

Topic 3.1 designed classes on paper; this topic shows what a class looks like in Java. Day 1 is the layout of a class (header, instance variables, constructor, methods) and the rule that every object has its own copy of each instance variable (3.3.A.2, 3.3.A.4). Day 2 is public and private: who may use each member, why instance variables are private (encapsulation), and why classes and constructors are public while methods can be either (3.3.A.1, 3.3.A.3, 3.3.A.5, 3.3.A.6).

Students know objects, references, new, and calling methods with a dot (Topics 1.12–1.14), and if statements (Topic 2.3). Stay inside the topic boundary. Every constructor has no parameters and simply gives each instance variable a starting value (writing constructors is Topic 3.4); every method is a short void method with no parameters (writing methods is Topic 3.5). Students read past static in main’s header; when the compiler message for Player.points mentions static, say that Topic 3.7 explains the word. Do not use this (Topic 3.9).

Teacher note

The slides are the Inside the Class deck (19 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–9 and Day 2 uses slides 10–19. The puzzle worksheet (9 questions, about 35 minutes) is split: questions 1–2 after Day 1, questions 3–9 after Day 2. The answers to the two Pause and Try slides (9 and 14) are in their speaker notes.

Every runnable example puts two classes in one file, so only the class with main is public. Say this once on Day 1 (slide 6) and point back to it whenever students ask why the second class has no public. Examples are in the topic’s examples/ folder.

  • Day 1 demonstrations: GameNight, TwoPublicClasses, TwoPlayers, SamePlayer, ClassNameField, PlayerTrace.
  • Day 2 demonstrations: PrivateOutside, PrivateInside, PublicScore, PrivateScore, GoalCounter, NoModifier, PrivateConstructor, ScoreReport, CallPrivateHelper, TimerBug, TimerFixed.
  • Exit ticket: uses ClickCounter and RidePass. Keep these out of class so the questions are new to students.

Day 1 · Warm-up: What can you reach?

Show slide 2. Pairs have two minutes to sort a vending machine’s parts into “customers can use” (buttons, coin slot, delivery door) and “locked inside” (cash box, motors, stock count), then say why the maker locks some parts away: so nobody can grab the money or set the stock count to a wrong number, and so the maker can change the motors without changing the buttons. Take two answers and park them on the board: they are Day 2’s public and private. Show the goals (slide 3); goals 1–3 are today’s.

Day 1 · Direct instruction: The parts of a class

  1. A class, part by part (3.3.A.2, slides 4–5). Walk the Stopwatch class top to bottom: the class header public class Stopwatch (the keyword class and the name), the instance variable seconds (declared inside the class but outside every constructor and method), the constructor (runs when new builds an object and gives seconds its starting value), and two methods. The usual order is instance variables, constructors, methods; Java does not require it, but every reader expects it.
  2. Run it. Open GameNight and have students name the part on each set of lines of Scoreboard before you run it: header (line 10), instance variables (12–14), constructor (16–21), method (23–26). Run it: Hawks 0, Visitors 0. Point out that inside the class, homeTeam on line 25 means “this object’s homeTeam.”
  3. Constructor or method? (slide 6). Two clues: a constructor has exactly the class’s name and no return type, not even void; a method has its own name and a return type. Ask: “What if I write public void Stopwatch()?” It compiles, but it is now a method that happens to share the class’s name, and new never runs it. Worksheet question 5 tests this.
  4. One public class per file (3.3.A.2). In this course every class is public and is declared with class, and each class lives in its own file named after it. Run TwoPublicClasses: class Scoreboard is public, should be declared in a file named Scoreboard.java. That is why the one-file examples leave public off the second class.

Misconception: Marking both classes public in one file

Students hear “every class is public” and write public on both classes of a one-file program. A file can hold only one public class, and it must have the file’s name. Show TwoPublicClasses and give the two fixes: leave public off the second class in a one-file program, or (as real projects and the AP exam do) put each class in its own file as public class Name.

Misconception: The lines in the constructor declare more instance variables

In seconds = 0; inside the constructor, students see a variable and count it again. A declaration starts with a type (private int seconds;); a line in the constructor without a type gives an existing instance variable a value. Count instance variables only between the class’s braces and outside every constructor and method.

Day 1 · Direct instruction: Every object has its own copy

  1. Instance variables belong to the object (3.3.A.4, slides 7–8). Each new Stopwatch() builds a separate object with its own seconds, starting at 0. On slide 8, three ticks on lap1 and one on lap2 print 3 s and 1 s. Draw the two boxes on the board as the slide does and update each one as you step through main.
  2. Reaching a variable from outside. Run TwoPlayers. This Player makes its variables public for now, so main can write ana.points: the reference, a dot, the name. Trace lines 7–11 in a two-column table (ana’s object, ben’s object). Line 11 changes only ana’s points: Ana has 15, Ben has 7. Tell students that tomorrow’s lesson is why real classes do not do this.
  3. Count objects, not variables. Run SamePlayer: three variables but only two objects, because second = first copies a reference (Topic 1.12). first.points and second.points are the same variable, so both print 20. The rule never changes: one copy per object.
  4. There is no class-wide copy. Run ClassNameField. Player.points = 12; does not compile (non-static variable points cannot be referenced from a static context). Say that static is Topic 3.7; the idea now is that Player.points does not say which player. Name the object: ana.points.

Misconception: The class holds one shared copy of each variable

Students picture points living in the class, so every Player shares it and Player.points makes sense. Count with them: one class, two objects, two points variables. Ask “Whose points?” every time a line changes one, and draw one box per object.

Misconception: Two variables always mean two objects

Player second = first; looks like a new player. Only new builds an object; assigning a reference makes two names for one object. SamePlayer is the demonstration, and question 4 of the study guide’s Pause and Try (“how many points variables exist?”) makes a good follow-up.

Day 1 · Guided practice: Whose cookies?

Slide 9. Students write both lines of output on mini whiteboards, then show on your signal: 9 cookies, then 8 cookies (a ate one, b ate two). Anyone who wrote 7 cookies twice treated cookies as one shared value; ask them to draw one box per jar. Then hand out the worksheet and give pairs the last few minutes for question 1 (label the parts of Aquarium). Check that they mark lines 4–7 as the constructor and say why (class name, no void).

Teacher note

If students finish quickly, project PlayerTrace and ask for its output (1, 14, 14): r and q name the same object, so line 10 changes Q and line 11 changes only P.

Day 1 · Independent practice: Independent practice

Puzzle worksheet questions 1–2 are homework: finish labeling Aquarium (question 1) and trace two Aquarium objects (question 2, answer A: 5 fish, then 4 fish). The Think First box on page 1 asks why a class would lock its data away; question 6 settles it after Day 2, so tell students to leave their guess in the margin.

Day 1 · Closure: Closure

Write on the board: Stopwatch a = new Stopwatch(); Stopwatch b = new Stopwatch(); Stopwatch c = a; and ask, “How many seconds variables exist, and why?” Students answer on a sticky note. Two: there are two news, so two objects, and c = a copies a reference.

Day 2 · Warm-up: Check question 2

Ask for the answer to worksheet question 2 by a show of fingers (1–4 for A–D). Discuss the two most common wrong answers: B (6 and 6) treats fishCount as one shared value, and D (3 and 3) forgets that addFish changes the object’s own instance variable. Then return to the vending machine on the board: “Today Java gets a lock.”

Day 2 · Direct instruction: Public and private

  1. Access modifiers (3.3.A.1, slides 10–11). public: any class may use it. private: only code inside the class that declares it, meaning between that class’s own braces. A member is anything declared directly in the class body: an instance variable, a constructor, or a method. The compiler checks this, so the mistake never reaches a user.
  2. Outside code hits the private door (slide 12). lap1.seconds = 99; in another class’s main does not compile: seconds has private access in Stopwatch. Then run PrivateOutside: line 6 (ana.name, public) compiles; line 7 (ana.points, private) does not, with the same kind of message. Read the message literally: points is private, and only Player has access.
  3. Private does not mean unusable. Run PrivateInside: Ana: 0 points. Line 24 reads the private points, and it compiles because line 24 is inside Player. main never names points; it calls the public printCard. Same variable, different line, different answer: what decides is the class the line is written in.
  4. Same file is not inside the class (slide 13). Have students put a finger on a line and ask, “Whose braces is this line between?” If it is not the class that declared the private member, the line cannot use it.

Misconception: Same file means inside the class

In one-file examples main sits a few lines above the private variable, so students count it as inside. private is about the class, not the file. Slide 13’s question (“Whose braces is this line between?”) is the fix, and worksheet question 4’s Fair Question box asks it again.

Misconception: A private variable cannot be used at all

Students conclude that private data is dead data. Contrast PrivateOutside (line 7 fails) with PrivateInside (line 24 compiles): private means usable only from inside, and the public methods are the way in.

Day 2 · Guided practice: Which lines compile?

Slide 14. Pairs decide for each of A–D whether it compiles in main after Robot r = new Robot();. Reveal from the speaker notes: A and C compile (name and charge are public; charge may call the private beep because it is inside Robot); B and D do not (battery has private access in Robot, beep() has private access in Robot). Ask a pair who said C does not compile to explain why, then ask the class whether calling a private helper from inside a public method makes the helper public. (No.)

Day 2 · Direct instruction: Encapsulation

  1. What goes wrong without it (slide 16). With a public seconds, any line can set a stopwatch to -30. Run PublicScore: Home -4, Away 0, an impossible score that nothing stopped. Then run PrivateScore: the same line now fails with homeScore has private access in Scoreboard.
  2. Encapsulation (3.3.A.1, 3.3.A.5). The implementation details of a class are kept hidden from other classes, which use only its public parts. Two benefits: protection (only the class’s own code changes its data, so if a value is ever wrong, only one class is a suspect) and freedom to change (the author can rename or rework private details without breaking other classes). Point back to the vending machine.
  3. Changing data through public methods. Run GoalCounter: homeGoal and awayGoal are the only ways in, so scores go up one at a time and never go negative. Home 2, Away 1.
  4. The rule. Mark every instance variable private unless the class’s specification (the written description of what the class must contain, such as an AP free-response prompt) says it is public. Worksheet question 3 practices exactly this.

Misconception: Leaving off the access modifier is the same as private

int homeScore; with no keyword compiles, so students skip the keyword. Run NoModifier: it prints Home -4, Away 0, because with no keyword a main in the same file can still reach it. Code without an access keyword never appears in AP exam answers; always write private.

Misconception: Private means the value never changes

Students hear “protected” and think “constant”. private limits who may change a variable, not whether it changes: homeGoal changes the private homeScore every call. Worksheet question 6 is built on this error (claim 2 is the lie).

Day 2 · Direct instruction: Access for classes, constructors, and methods

  1. Who wears which keyword (3.3.A.2, 3.3.A.3, 3.3.A.6, slide 17). Go row by row. Classes: public. Constructors: public, because other classes must be able to build objects; run PrivateConstructor (Scoreboard() has private access in Scoreboard): without the constructor, main cannot get a Scoreboard at all. Instance variables: private unless the specification says otherwise. Methods: public when other classes call them (services such as tick), private when only the class’s own code calls them (helper methods).
  2. A private helper. Run ScoreReport: the public printScores calls the private printDivider twice, and it works because the call is inside Scoreboard. Then run CallPrivateHelper: the same method called from main gives printDivider() has private access in Scoreboard. The method did not change; the location of the call did.
  3. Quick fix. Project TimerBug and ask for a fix that changes only main: call the public finish instead of the private beep. Run TimerFixed to confirm (30 seconds are up, BEEP). Making beep public would compile too, but it gives away a helper the class meant to keep hidden. Worksheet question 7 is the same puzzle with a doorbell.

Misconception: Make everything private to be safe

After encapsulation, students mark methods private too. “Private by default” applies to instance variables. For a method, ask who calls it: if another class does, it must be public. A private printScores compiles, but every field.printScores(); in main then fails with printScores() has private access in Scoreboard.

Misconception: A private class hides the data

Students who want to hide data sometimes write private class Score, which does not compile for a class on its own (modifier private not allowed here). Classes are always public in this course; the data is hidden by making the instance variables private.

Day 2 · Independent practice: Independent practice

Puzzle worksheet questions 3–9 are homework, about 25 minutes: write the Plant header and instance variables from a specification (question 3), be the compiler at the private door (question 4), fill the constructor hole from the snippet pool (question 5), two truths and a lie about a private balance (question 6), a one-token fix to a private method call (question 7), the Public and Private face-off (question 8), and Who Am I (question 9). Question 6 answers the Think First box from page 1.

Day 2 · Closure: Closure and exit ticket

Slide 18 (vocabulary) is a quick check: point to a card and have a student find that part in the Stopwatch class. Then slide 19: partners finish the sentence starter (“Instance variables are private so that _. The constructor is public so that _.”) and you cold-call two pairs; listen for “only code inside the class can change them” and “so other classes can build objects with new.” Give the exit ticket (about five minutes). Question 1 checks that each object has its own copy of an instance variable (3.3.A.4), question 2 checks which members outside code may use (3.3.A.1, 3.3.A.3, 3.3.A.6), and question 3 checks the access choices for instance variables and constructors (3.3.A.3, 3.3.A.5). Re-teach the weakest one at the start of Topic 3.4.

Exit ticket

Question 1 · Multiple choice

What does this program print?

ClickCounter.java
public class ClickCounter
{
    public static void main(String[] args)
    {
        Counter x = new Counter();
        Counter y = new Counter();
        Counter z = x;
        x.click();
        z.click();
        y.click();
        x.printClicks();
        y.printClicks();
    }
}

class Counter
{
    private int clicks;

    public Counter()
    {
        clicks = 2;
    }

    public void click()
    {
        clicks = clicks + 3;
    }

    public void printClicks()
    {
        System.out.println(clicks);
    }
}
  1. 5, then 5 on the next line
  2. 8, then 5 on the next line
  3. 11, then 11 on the next line
  4. 6, then 3 on the next line
Check your reasoning

B. Lines 5 and 6 build two Counter objects, each with its own clicks starting at 2. Line 7 copies x’s reference, so z names the same object as x; no new object is built.

Line Statement x’s object (x, z) y’s object
5–7 build, copy 2 2
8 x.click() 5 2
9 z.click() 8 2
10 y.click() 8 5
  • A treats z as a third object, so z.click() does not change x’s object.
  • C treats clicks as one value shared by every Counter, so all three calls add to it.
  • D skips the constructor and starts clicks at 0, but new runs the constructor, which sets it to 2.

Question 2 · Multiple choice

Each statement below is added, on its own, to main in RidePass after line 5. Which of them compile?

RidePass.java
public class RidePass
{
    public static void main(String[] args)
    {
        Pass p = new Pass();
        p.ride();
        p.printPass();
    }
}

class Pass
{
    public String holder;
    private int rides;

    public Pass()
    {
        holder = "Guest";
        rides = 10;
    }

    public void ride()
    {
        rides = rides - 1;
        logRide();
    }

    public void printPass()
    {
        System.out.println(holder + ": " + rides + " rides left");
    }

    private void logRide()
    {
        System.out.println("Ride recorded");
    }
}
  • I. p.holder = "Lee";
  • II. p.logRide();
  • III. p.ride();
  1. I only
  2. II only
  3. I and III only
  4. I, II, and III
Check your reasoning

C. holder and ride are public, so code in any class may use them. logRide is private, and main is in a different class, RidePass, so II fails with logRide() has private access in Pass. A leaves out III, but ride is public; that it calls a private helper inside Pass does not stop outside code from calling it. B has it backwards: II is the one statement that does not compile. D includes II; being in the same file does not put main inside Pass, and being called by ride does not make logRide public.

Question 3 · Multiple choice

A teammate writes a Thermostat class whose specification says only “a Thermostat has a double target temperature.” Which pair of declarations should the class use?

  1. private double target; and the constructor public Thermostat()
  2. public double target; and the constructor public Thermostat()
  3. private double target; and the constructor private Thermostat()
  4. public double target; and the constructor private Thermostat()
Check your reasoning

A. Instance variables are private unless the specification says otherwise, so only Thermostat’s own code can change them (encapsulation). Constructors are public in this course, because other classes must be able to build objects with new.

  • B makes target public, so any class could set it to a nonsense value; the specification does not say it is public.
  • C makes the constructor private, so new Thermostat() in another class does not compile and no other class could get a Thermostat at all. Private is right for the variable, not for everything.
  • D gets both backwards: the data is open to every class, and no other class can build an object.