Overview
A class variable is declared with static, belongs to the class, and has exactly one copy shared by every object (3.7.A.1). A public class variable is used from another class as ClassName.variableName (3.7.A.1). A final variable cannot be changed once it has a value, and a public static final variable is a class constant (3.7.A.2). A class method has static in its header, may read and change class variables and call other class methods (3.7.B.1, 3.7.B.2), and cannot use instance variables or instance methods unless it is handed an object through a parameter (3.7.B.3).
Day 1: one shared copy, and the counter that silently counts to 1 without static. Day 2: reaching a public class variable from main, final and class constants, and writing class methods. Day 3: what a class method cannot reach, and how a parameter fixes it.
Students know how to write classes with private instance variables, constructors, accessors, and mutators (3.3–3.5), and that a method may use the private data of a parameter of its own class (3.6). They have called class methods such as Math.sqrt and used Integer.MAX_VALUE (1.5, 1.10). Stay inside the boundary: no this (Topic 3.9), no arrays or ArrayList (Unit 4). Where a variable may be used inside a class (scope) is Topic 3.8; answer scope questions with “next topic.”
One question runs through all three days, and the study guide uses it too: “Is this value about one object, or about all of them?” About all of them means static.
Teacher note
The slides are the One Copy for Everyone deck (21 slides, with speaker notes); slide numbers below refer to it. Slides 4, 9, 13, and 16 are part dividers. Day 1 uses slides 1–8, Day 2 slides 9–15, and Day 3 slides 16–21.
The One Copy for Everyone puzzle worksheet (9 questions, about 30 minutes) is homework, split by day: question 2 after Day 1; questions 1, 3, 6, and 8 after Day 2; questions 4, 5, 7, and 9 after Day 3. The Think First box (a game’s coin total) is settled by questions 1 and 2; assign it with question 2 on Day 1.
Demonstrations are in the topic’s examples/ folder. Each file holds the object class and a separate class with main, so one click runs it: MemberCount, MemberNoStatic, TeamScore (Day 1); RaffleSales, RafflePrivate, RaffleNoClassName, PizzaParty, FinalChange, RaffleReport, GradeCheck, RaffleMissingStatic (Day 2); StaticReadsInstance, MemberDescribe, HigherScorer, ThermostatBug, ThermostatFixed, OrderNumbers (Day 3). Open each day’s files in the IDE before class.
Day 1 · Warm-up: Whose number is it?
Show slide 2. Pairs sort the four bus facts into “one bus” and “all of the buses.” The driver’s name and the riders on this bus today belong to one bus; the riders on all buses today and the seats per bus belong to all of them. Ask: “If every bus kept its own copy of the riders-on-all-buses number, could any one bus know the right total?” No: each bus would only know its own riders. Keep the sorted lists on the board for the closure.
Day 1 · Direct instruction: One shared copy
- Goals (slide 3). Read the five goals aloud. Goal 1 is today’s, goals 2–4 are Day 2’s, and goal 5 is Day 3’s.
- Instance variable or class variable? (3.7.A.1, slide 5). An instance variable gets one copy per object; a class variable, declared with
staticbefore the type, has one copy for the whole class, shared by every object. Point at the two declarations: the only difference is the wordstatic. Remind students they metstaticin Topic 1.10 on class methods; on a variable it means the same thing, “this belongs to the class.” - Two buses, one total (slide 6). Before revealing the output, ask students to predict all three lines.
northboards 10 and then 4, so its ownridersis 14;southhas 6.south.getAll()prints 20 becausetotalRiderscounts north’s riders too: there is only one copy. Draw the memory picture: two bus objects, each with its ownriders, and onetotalRidersdrawn outside both, beside the class name. - Starting value on the declaration line. Ask: “Why is
totalRiders = 0written in the declaration and not in the constructor?” A constructor runs once for every new object, so setting the count there would wipe it out each time a bus is made. A class variable is set up once. - A counter without
staticcounts to 1 (slide 7). Ask students whatkit.getCount()prints in each version before you say. Withoutstatic, eachPethas its ownpetCount, raised from 0 to 1 by its own constructor, so it prints 1; withstatic, it prints 3. Stress the last line of the slide: no error warns you.
Misconception: A counter without static still counts every object
Students write private int count = 0; and expect the constructor’s count++ to count all objects. It compiles and runs, so nothing tells them it is wrong; every object just counts itself and reports 1. Run MemberNoStatic in guided practice and let students see 1 1 1 1. Then give them the question to ask of every new variable: “Is this value about one object, or about all of them?”
Misconception: Resetting a class variable in the constructor
Some students put totalRiders = 0; in the constructor “to start it off.” Then every new object resets the shared total. Point back to step 4: the constructor runs once per object, so the starting value of a class variable goes on its declaration line. Worksheet question 2 has a Fair Question on exactly this.
Day 1 pause and try
Slide 8 (sip, sip, sip). Students write both lines on mini whiteboards before anyone answers. a.getSips() is 1, because a sipped once and sips is its own; a.getAll() is 3, because allSips counts b’s two sips as well. Students who write 1 then 1 are treating allSips as a’s own copy; send them back to the memory picture from slide 6.
Day 1 · Guided practice: Guided practice
- Students run
MemberCountand match each printed line to the trace in the guide: line 25 prints 2 even though nothing was done to Ana’s object, because there is no count stored inside it. - Students delete
staticfrom line 4 and run it again (theMemberNoStaticresult:1 1 1 1). Ask: “Did the compiler complain? Why is every line 1?” Then putstaticback. - Students run
TeamScore, then add one morescorePointscall of their own and predict the three printed values before running. Each call changes only one player’spoints, but every call changes the oneteamPoints.
Teacher note
If computers are not ready, run step 2 as a whole-class demo: delete the word, run, and put it back. It is the one demonstration of Day 1 that students must see.
Day 1 · Independent practice: Independent practice
Puzzle worksheet question 2 (the Lantern JVM trace) and the Think First box are homework. Question 1 waits until after Day 2, because its last blank needs the class name and dot taught on Day 2.
Day 1 · Closure: Closure
Cold-call with three quick cases, each answered “one object” or “all of them”: a car’s mileage (one object, instance variable); the number of cars made so far (all of them, static); the number of wheels every car has (all of them, static, and it never changes, which is where Day 2 starts).
Day 2 · Warm-up: Where have you seen ClassName.NAME?
Write Integer.MAX_VALUE and Math.sqrt(16) on the board. Ask: “What is to the left of the dot? Did you ever make an Integer or a Math object?” The class name; no. Both reach something that belongs to the class, so no object is needed. Then go over worksheet question 2 from homework: a’s own glow is 3, and b.getLit() reads the one shared lit, 3. Students who wrote 3 1 treated lit as b’s own copy.
Day 2 · Direct instruction: Class name and dot, final, class constants
- Class name, dot, variable name (3.7.A.1, slides 9–10). A
publicclass variable is used from another class asClassName.variableName; inside its own class, the name alone works. Ask what the firstprintlnon slide 10 prints before anyScoreobject exists: 0. A class variable is not stored in objects, so it exists as soon as the class is used. Then 95, the highest of 70, 95, and 80. - The danger of public (live demo). Run
RaffleSales: line 21 setsRaffle.ticketsSold = 0frommain, and the count says 0 even though two tickets exist. This is why Topic 3.3 recommendsprivate. Then runRafflePrivate: the class name is the right form, butprivatestill blocks it (ticketsSold has private access in Raffle). final(3.7.A.2, slide 11). Afinalvariable cannot be changed once it has a value. Read the declaration word by word:public(anyone may read it),static(one copy, for the class),final(it can never change). Apublic static finalvariable is a class constant, by custom named in capitals. Show that insideTeam,openSpotsusesMAX_SIZEby name alone, whilemainwritesTeam.MAX_SIZE. RunPizzaPartyfor a second constant.finalis not only for class variables. Mention, without a demo, that an instance variable can befinaltoo: each student’s ID set once in the constructor. Worksheet question 6 uses one.- public does not mean “anyone can change it” (slide 12). Run
FinalChangeto show the compiler message. Walk the table row by row:public staticcan be read and changed frommain;private staticcannot be read frommain;public static finalcan be read but not changed.
Misconception: Leaving off the class name outside the class
Inside Raffle, the constructor writes ticketsSold alone, so students write the same in main and get cannot find symbol. Java looks for ticketsSold in main and in main’s own class and finds nothing. Run RaffleNoClassName, then fix line 18 to Raffle.ticketsSold. The rule: from another class, class name and dot; inside the declaring class, the name alone.
Misconception: A class variable always needs its class name
The reverse error: once students learn ClassName.variable, some think code inside the class must write it too, and mark correct code as wrong. Worksheet question 8’s lie is built on this. Point at openSpots on slide 11: inside Team, MAX_SIZE alone compiles.
Misconception: public means anyone can change it
Students read public as permission to assign, so they try Team.MAX_SIZE = 6; to model a bigger team. public decides who may read the constant; final stops everyone from changing it, including its own class. If a value really needs to vary, it should not be final.
Day 2 · Direct instruction: Writing class methods
- Class methods work on class data (3.7.B.1, 3.7.B.2, slides 13–14). A class method is written like any method from Topic 3.5 with
staticbefore the return type. It may read and change class variables and call other class methods, so it needs no object. Trace slide 14:play(8)andplay(4)change the sharedtokensUsedto 12,getUsed()reads it, andspent()calls the class methodgetUsed()and multiplies byFEE: 12 × 0.25 is 3.0. - Live demo. Run
RaffleReport:ticketsSoldisprivateagain, and two class methods give controlled access, one that reads it and one that resets it. Compare withRaffleSales: the count can still be reset, but only through a method the class chose to provide. If time allows, showGradeCheck, a class with no instance variables that works likeMath.
Misconception: Calling a method through the class name without making it static
Students write public int getTicketsSold() and call Raffle.getTicketsSold(). Without static it is an instance method and must be called on an object, so the compiler reports non-static method getTicketsSold() cannot be referenced from a static context. Guided practice fixes exactly this.
Day 2 pause and try
Slide 15 (score the quiz). Students write the output and one sentence for the “why.” Three answers add 23 points over 3 questions, and points / asked is integer division, so it prints 7, not 7.67. No Quiz object is ever needed because every variable and method in Quiz is static: everything belongs to the class. Students who write 7.666… have forgotten that both operands are int (Topic 1.3).
Day 2 · Guided practice: Guided practice
Students open RaffleMissingStatic and run it. The compiler reports the same error at lines 27, 31, and 33. Pairs decide: is the fix in main (make an object and call the method on it) or in the method header (add static)? Both compile, but the count is about all tickets, not one ticket, so static is the right fix. Add it, run, and compare with RaffleReport.
Day 2 · Independent practice: Independent practice
Puzzle worksheet questions 1, 3, 6, and 8 are homework: the instance-versus-class face-off, the Kiosk code tiles (with two decoys that don’t compile), the one-word fix for the locker numbers, and the Gym two truths and a lie.
Day 2 · Closure: Closure
Each student writes one sentence for each word in public static final int MAX_SIZE = 5;: who may read it, how many copies there are, and whether it can change. Collect three or four and read them aloud.
Day 3 · Warm-up: Why did the Kiosk decoys fail?
Put worksheet question 3’s two decoy tiles on the board: System.out.println(Kiosk.sold); and System.out.println(getSold());. Ask why each one fails from main. The first is private, so the class name doesn’t get around it; the second is in another class, so it needs Kiosk.getSold(). Then ask: “Which variables did every Kiosk method use?” Only class variables. Today: what happens when a class method reaches for an instance variable.
Day 3 · Direct instruction: A class method has no object of its own
- The question Java can’t answer (3.7.B.3, slides 16–17). Show
Dog.greet()on slide 17 and ask, before revealing the compiler message: “Whosename? There might be a hundred dogs, or none.” Java does not guess, so the code does not compile. “Static context” means “inside a class method, where there is no current object.” RunStaticReadsInstanceto see the same message. - The table on slide 17. Inside a class method: class variables, yes; other class methods, yes; instance variables or instance methods by name alone, no; through an object parameter, yes.
- Hand the class method an object (slide 18).
greet(Dog d)names the dog it means,d.name.nameis private, butgreetis insideDoganddis aDog, so it is allowed (Topic 3.6).olderreceives two dogs and returns the reference to the older one: Bo is 7, soDog.greet(big)printsHi, Bo. RunMemberDescribe(a class method that calls an instance method on its parameter and changes an instance variable through it), andHigherScorerif time allows. - Why
mainalways makes an object first.mainis a class method too, so it has no object of its own; that is why it makes objects and calls instance methods on them. Instance methods and constructors have no such limit: they may use class variables freely, as thePetconstructor did.
Misconception: Adding static just to call a method without an object
A student sees that Dog.greet() is easy to call and makes a method static even though it needs one object’s data. The result is the non-static variable … cannot be referenced from a static context error. Before writing static on a method, ask: “Does this method need one object’s instance variables?” If yes, leave it an instance method or give it a parameter of the class.
Misconception: Making the instance variable static to silence the error
When a class method can’t read temperature, some students add static to temperature instead. It compiles, but now every thermostat shares one temperature, which is a logic error. Ask the Day 1 question again: is a room’s temperature about one thermostat or all of them? The fix is a parameter, not static on the variable.
Day 3 pause and try
Slide 19 (which bodies compile?). Students vote with fingers for each body. A (return dogCount;) compiles: a class method may read a class variable. D (return countDogs();) compiles: it may call another class method. B (return age;) and C (return getAge();) do not: an instance variable and an instance method need an object, and the method has no parameter. Ask how to make B work: give the method a Dog parameter and return d.age.
Day 3 · Guided practice: Guided practice
- Pairs open
ThermostatBug, run it, and read the message at line 13. They fixisTooHotso it can still be called asThermostat.isTooHot(...): add aThermostatparameter, useroom.temperature, and change the call inmainto passkitchen. Compare withThermostatFixed; it printstrue. - With the time left, trace
OrderNumberstogether on the board (the guide’s Putting it together). Before tracing, have students sort its variables: shared class variables (nextNumber,ordersPlaced), a class constant, afinalinstance variable set once per order, and a class method that compares two orders through its parameters. Every idea of the topic is in it.
Day 3 · Independent practice: Independent practice
Puzzle worksheet questions 4, 5, 7, and 9 are homework: the Plant snippet pool (needsWater must be handed a plant), the Lamp you’re-the-compiler table, Who Am I?, and the wrap-up reflection.
Day 3 · Closure: Closure and exit ticket
Spend two minutes on slide 20 (vocabulary): cover the definitions and have students define each term in their own words. Then slide 21: partners decide whether each song’s title or the number of songs in the app should be static and use the sentence starter (the number of songs, because it describes all songs, not one song). Give the exit ticket (about five minutes). Question 1 checks a shared class variable and a class method that calls another class method (3.7.A.1, 3.7.B.1, 3.7.B.2), question 2 a class method that reaches for an instance variable (3.7.B.3), and question 3 choosing static and final for a class’s variables (3.7.A.1, 3.7.A.2). Re-teach the weakest one at the start of Topic 3.8.