Skip to content

Course navigation

For teachersTopic 3.7 · Lesson kit

Class Variables and Methods

  • 3 class periods
  • 45 minutes each
  • Objectives 3.7.A, 3.7.B
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    3 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
3 class periods of 45 minutes
Learning objectives
3.7.A3.7.B
Essential knowledge
3.7.A.13.7.A.23.7.B.13.7.B.23.7.B.3
Materials
Projector and the One Copy for Everyone slide deckWhiteboard and markersMini whiteboards or scrap paperIDE on every computer (Days 1 to 3)Printed One Copy for Everyone puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Activity
  1. 0:00–0:055 minWarm-upwhose number is it? (slide 2)
  2. 0:05–0:2217 minDirect instructionone shared copy; a counter without static (slides 3–7)
  3. 0:22–0:275 minActivityDay 1 pause and try — sip, sip, sip (slide 8)
  4. 0:27–0:4013 minGuided practicerun MemberCount, remove static, then TeamScore
  5. 0:40–0:455 minClosureone object, or all of them?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Activity
  1. 0:00–0:055 minWarm-upwhere have you seen ClassName.NAME?
  2. 0:05–0:2015 minDirect instructionclass name and dot, final, class constants (slides 9–12)
  3. 0:20–0:288 minDirect instructionwriting class methods (slides 13–14)
  4. 0:28–0:335 minActivityDay 2 pause and try — score the quiz (slide 15)
  5. 0:33–0:407 minGuided practicefix RaffleMissingStatic in the IDE
  6. 0:40–0:455 minClosurepublic, static, final in one sentence each

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Exit ticket
  • Activity
  1. 0:00–0:055 minWarm-upwhy did the Kiosk decoys fail?
  2. 0:05–0:2015 minDirect instructiona class method has no object of its own (slides 16–18)
  3. 0:20–0:255 minActivityDay 3 pause and try — which bodies compile? (slide 19)
  4. 0:25–0:3510 minGuided practicefix ThermostatBug, then trace OrderNumbers
  5. 0:35–0:405 minClosurevocabulary and one object or all of them (slides 20–21)
  6. 0:40–0:455 minExit ticket

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

  1. 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.
  2. Instance variable or class variable? (3.7.A.1, slide 5). An instance variable gets one copy per object; a class variable, declared with static before the type, has one copy for the whole class, shared by every object. Point at the two declarations: the only difference is the word static. Remind students they met static in Topic 1.10 on class methods; on a variable it means the same thing, “this belongs to the class.”
  3. Two buses, one total (slide 6). Before revealing the output, ask students to predict all three lines. north boards 10 and then 4, so its own riders is 14; south has 6. south.getAll() prints 20 because totalRiders counts north’s riders too: there is only one copy. Draw the memory picture: two bus objects, each with its own riders, and one totalRiders drawn outside both, beside the class name.
  4. Starting value on the declaration line. Ask: “Why is totalRiders = 0 written 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.
  5. A counter without static counts to 1 (slide 7). Ask students what kit.getCount() prints in each version before you say. Without static, each Pet has its own petCount, raised from 0 to 1 by its own constructor, so it prints 1; with static, 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

  1. Students run MemberCount and 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.
  2. Students delete static from line 4 and run it again (the MemberNoStatic result: 1 1 1 1). Ask: “Did the compiler complain? Why is every line 1?” Then put static back.
  3. Students run TeamScore, then add one more scorePoints call of their own and predict the three printed values before running. Each call changes only one player’s points, but every call changes the one teamPoints.

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

  1. Class name, dot, variable name (3.7.A.1, slides 9–10). A public class variable is used from another class as ClassName.variableName; inside its own class, the name alone works. Ask what the first println on slide 10 prints before any Score object 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.
  2. The danger of public (live demo). Run RaffleSales: line 21 sets Raffle.ticketsSold = 0 from main, and the count says 0 even though two tickets exist. This is why Topic 3.3 recommends private. Then run RafflePrivate: the class name is the right form, but private still blocks it (ticketsSold has private access in Raffle).
  3. final (3.7.A.2, slide 11). A final variable 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). A public static final variable is a class constant, by custom named in capitals. Show that inside Team, openSpots uses MAX_SIZE by name alone, while main writes Team.MAX_SIZE. Run PizzaParty for a second constant.
  4. final is not only for class variables. Mention, without a demo, that an instance variable can be final too: each student’s ID set once in the constructor. Worksheet question 6 uses one.
  5. public does not mean “anyone can change it” (slide 12). Run FinalChange to show the compiler message. Walk the table row by row: public static can be read and changed from main; private static cannot be read from main; public static final can 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

  1. 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 static before 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) and play(4) change the shared tokensUsed to 12, getUsed() reads it, and spent() calls the class method getUsed() and multiplies by FEE: 12 × 0.25 is 3.0.
  2. Live demo. Run RaffleReport: ticketsSold is private again, and two class methods give controlled access, one that reads it and one that resets it. Compare with RaffleSales: the count can still be reset, but only through a method the class chose to provide. If time allows, show GradeCheck, a class with no instance variables that works like Math.

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

  1. 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: “Whose name? 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.” Run StaticReadsInstance to see the same message.
  2. 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.
  3. Hand the class method an object (slide 18). greet(Dog d) names the dog it means, d.name. name is private, but greet is inside Dog and d is a Dog, so it is allowed (Topic 3.6). older receives two dogs and returns the reference to the older one: Bo is 7, so Dog.greet(big) prints Hi, Bo. Run MemberDescribe (a class method that calls an instance method on its parameter and changes an instance variable through it), and HigherScorer if time allows.
  4. Why main always makes an object first. main is 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 the Pet constructor 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

  1. Pairs open ThermostatBug, run it, and read the message at line 13. They fix isTooHot so it can still be called as Thermostat.isTooHot(...): add a Thermostat parameter, use room.temperature, and change the call in main to pass kitchen. Compare with ThermostatFixed; it prints true.
  2. With the time left, trace OrderNumbers together on the board (the guide’s Putting it together). Before tracing, have students sort its variables: shared class variables (nextNumber, ordersPlaced), a class constant, a final instance 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.

Exit ticket

Question 1 · Multiple choice

This program prints three lines. Which choice gives them in order?

BoothSales.java
class Booth
{
    public static final int PRICE = 3;
    private static int totalSold = 0;
    private int sold;

    public Booth()
    {
        sold = 0;
    }

    public void sell(int tickets)
    {
        sold += tickets;
        totalSold += tickets;
    }

    public int getSold()
    {
        return sold;
    }

    public static int getTotalSold()
    {
        return totalSold;
    }

    public static int earnings()
    {
        return getTotalSold() * PRICE;
    }
}

public class BoothSales
{
    public static void main(String[] args)
    {
        Booth east = new Booth();
        Booth west = new Booth();
        east.sell(4);
        west.sell(2);
        east.sell(1);
        System.out.println(east.getSold());
        System.out.println(Booth.getTotalSold());
        System.out.println(Booth.earnings());
    }
}
  1. 5, 5, 15
  2. 7, 7, 21
  3. 5, 7, 15
  4. 5, 7, 21
Check your reasoning

D. sold is an instance variable, so each booth has its own; totalSold is a class variable, one copy shared by both booths.

Statement east.sold west.sold totalSold
east.sell(4) 4 0 4
west.sell(2) 4 2 6
east.sell(1) 5 2 7

east.getSold() is 5. Booth.getTotalSold() reads the shared 7, which includes west’s 2. Booth.earnings() calls the class method getTotalSold() and multiplies by the class constant: 7 × 3 is 21.

  • A treats totalSold as east’s own, leaving out west’s 2 tickets.
  • B treats sold as shared too, but without static each booth has its own copy.
  • C has the right total but computes earnings from east’s own sold (5 × 3). earnings uses getTotalSold(), the shared 7.

Question 2 · Multiple choice

This program does not compile: non-static variable battery cannot be referenced from a static context. Which change fixes it so that isLow can still be called through the class name?

PhoneBattery.java
class Phone
{
    public static final int LOW = 20;
    private int battery;

    public Phone(int charge)
    {
        battery = charge;
    }

    public static boolean isLow()
    {
        return battery < LOW;
    }
}

public class PhoneBattery
{
    public static void main(String[] args)
    {
        Phone mine = new Phone(15);
        System.out.println(Phone.isLow());
    }
}
  1. Change line 4 to private static int battery;
  2. Change line 11 to public static boolean isLow(Phone p), line 13 to return p.battery < LOW;, and line 22 to System.out.println(Phone.isLow(mine));
  3. Change line 13 to return Phone.battery < LOW;
  4. Change line 4 to public int battery;
Check your reasoning

B. A class method has no phone of its own, so it cannot use the instance variable battery by name alone. Passing a Phone tells it whose battery to check; p.battery is allowed because isLow is inside Phone. With the fix it prints true (15 < 20).

  • A compiles, but now every phone shares one battery level, which is wrong: a battery belongs to one phone.
  • C still names no object; battery is not a class variable, so the class name doesn’t help.
  • D changes who may access battery, not whose battery it is; the same error remains.

Question 3 · Multiple choice

A Ticket class for a concert needs three variables: each ticket’s seat number, the number of tickets sold so far, and the hall’s capacity, 500, which is the same for every ticket and never changes. Which set of declarations is correct?

  1. private int seat;, private static final int ticketsSold = 0;, public static final int CAPACITY = 500;
  2. private static int seat;, private static int ticketsSold = 0;, public static final int CAPACITY = 500;
  3. private int seat;, private static int ticketsSold = 0;, public static final int CAPACITY = 500;
  4. private int seat;, private int ticketsSold = 0;, public final int CAPACITY = 500;
Check your reasoning

C. Each ticket has its own seat, so seat is an instance variable: no static. The count is about all tickets, so it has one shared copy (static), and it is not final because it changes with every sale. The capacity is one value for all tickets (static) that can never change (final): a class constant, so it is safe to make public.

  • A makes the count final, so it stays 0 forever; any statement that adds a sale does not compile.
  • B makes seat static, so every ticket shares one seat number, and setting one ticket’s seat changes them all.
  • D leaves out static, so each ticket keeps its own count (each one only knows about itself) and its own copy of the capacity.