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
ClickCounterandRidePass. 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
- A class, part by part (3.3.A.2, slides 4–5). Walk the
Stopwatchclass top to bottom: the class headerpublic class Stopwatch(the keywordclassand the name), the instance variableseconds(declared inside the class but outside every constructor and method), the constructor (runs whennewbuilds an object and givessecondsits starting value), and two methods. The usual order is instance variables, constructors, methods; Java does not require it, but every reader expects it. - Run it. Open
GameNightand have students name the part on each set of lines ofScoreboardbefore 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,homeTeamon line 25 means “this object’shomeTeam.” - 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 writepublic void Stopwatch()?” It compiles, but it is now a method that happens to share the class’s name, andnewnever runs it. Worksheet question 5 tests this. - One public class per file (3.3.A.2). In this course every class is
publicand is declared withclass, and each class lives in its own file named after it. RunTwoPublicClasses:class Scoreboard is public, should be declared in a file named Scoreboard.java. That is why the one-file examples leavepublicoff 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
- Instance variables belong to the object (3.3.A.4, slides 7–8). Each
new Stopwatch()builds a separate object with its ownseconds, starting at 0. On slide 8, three ticks onlap1and one onlap2print3 sand1 s. Draw the two boxes on the board as the slide does and update each one as you step throughmain. - Reaching a variable from outside. Run
TwoPlayers. ThisPlayermakes its variablespublicfor now, somaincan writeana.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 onlyana’s points:Ana has 15,Ben has 7. Tell students that tomorrow’s lesson is why real classes do not do this. - Count objects, not variables. Run
SamePlayer: three variables but only two objects, becausesecond = firstcopies a reference (Topic 1.12).first.pointsandsecond.pointsare the same variable, so both print20. The rule never changes: one copy per object. - 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 thatstaticis Topic 3.7; the idea now is thatPlayer.pointsdoes 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
- 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. - Outside code hits the private door (slide 12).
lap1.seconds = 99;in another class’smaindoes not compile:seconds has private access in Stopwatch. Then runPrivateOutside: line 6 (ana.name, public) compiles; line 7 (ana.points, private) does not, with the same kind of message. Read the message literally:pointsis private, and onlyPlayerhas access. - Private does not mean unusable. Run
PrivateInside:Ana: 0 points. Line 24 reads the privatepoints, and it compiles because line 24 is insidePlayer.mainnever namespoints; it calls the publicprintCard. Same variable, different line, different answer: what decides is the class the line is written in. - 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
- What goes wrong without it (slide 16). With a public
seconds, any line can set a stopwatch to-30. RunPublicScore:Home -4, Away 0, an impossible score that nothing stopped. Then runPrivateScore: the same line now fails withhomeScore has private access in Scoreboard. - 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.
- Changing data through public methods. Run
GoalCounter:homeGoalandawayGoalare the only ways in, so scores go up one at a time and never go negative.Home 2, Away 1. - The rule. Mark every instance variable
privateunless 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
- 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; runPrivateConstructor(Scoreboard() has private access in Scoreboard): without the constructor,maincannot get aScoreboardat all. Instance variables:privateunless the specification says otherwise. Methods:publicwhen other classes call them (services such astick),privatewhen only the class’s own code calls them (helper methods). - A private helper. Run
ScoreReport: the publicprintScorescalls the privateprintDividertwice, and it works because the call is insideScoreboard. Then runCallPrivateHelper: the same method called frommaingivesprintDivider() has private access in Scoreboard. The method did not change; the location of the call did. - Quick fix. Project
TimerBugand ask for a fix that changes onlymain: call the publicfinishinstead of the privatebeep. RunTimerFixedto confirm (30 seconds are up,BEEP). Makingbeeppublic 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.