Skip to content

Course navigation

For teachersTopic 3.9 · Lesson kit

this Keyword

  • 2 class periods
  • 45 minutes each
  • Objective 3.9.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.9.A
Essential knowledge
3.9.A.13.9.A.23.9.A.3
Materials
Projector and the Who Is this? slide deckWhiteboard and markersMini whiteboards or scrap paper (call tables)IDE on the projector (student computers optional)Printed Who Is this? 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-upwho is "I"? (slide 2)
  2. 0:05–0:1712 minDirect instructionthis is the current object (slides 3–7)
  3. 0:17–0:258 minGuided practicewhose coins? (slide 8) and worksheet question 2
  4. 0:25–0:3712 minDirect instructionreaching a hidden instance variable (slides 9–12)
  5. 0:37–0:425 minGuided practicedid the tank fill up? (slide 13)
  6. 0:42–0:453 minClosurewhich side gets this?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upthe player with no name
  2. 0:05–0:1510 minDirect instructionpassing this along (slides 14–16)
  3. 0:15–0:238 minGuided practiceworksheet question 4
  4. 0:23–0:318 minDirect instructionclass methods have no this (slides 17–18)
  5. 0:31–0:376 minGuided practicewhich methods compile? (slide 19) and worksheet question 5
  6. 0:37–0:403 minClosuresay it in your own words (slides 20–21)
  7. 0:40–0:455 minExit ticket

Overview

This is the last topic of Unit 3, and it has one learning objective (3.9.A): write and trace self-referencing expressions, the ones that use this. Day 1 is what this holds (3.9.A.1): inside an instance method or a constructor, this is a reference to the current object, the object the method was called on or the one a constructor is building. Students then use this.name to reach an instance variable that a parameter with the same name hides. Day 2 is the other two uses: passing this as an argument so another method can work with the current object (3.9.A.2), and the fact that class methods have no this (3.9.A.3).

Keep one question running through both days: “Which object is before the dot?” That answers what this is in every call. The study guide uses a microphone picture for the same idea (whoever holds the microphone is “I”); the warm-up is built on it.

Students already have everything this topic leans on: instance methods called with a dot (Topic 3.5), reference parameters that copy the reference and not the object (Topic 3.6), class variables and class methods (Topic 3.7), shadowing by a parameter or local variable (Topic 3.8), and == on references (Topic 2.6). Stay inside the boundary: Unit 4 (arrays, ArrayList) has not started, and the CED does not ask for calling one constructor from another with this(...); do not teach it.

Teacher note

The slides are the Who Is this? deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–13 and Day 2 uses slides 14–21. The Who Is this? puzzle worksheet (8 questions, about 30 minutes) is split across the two days: question 2 in class on Day 1, questions 1 and 3 as Day 1 homework, questions 4 and 5 in class on Day 2, and questions 6, 7, and 8 as Day 2 homework (with whatever is left of question 5).

The slide code (Badge, Piggy, Book, Trip, Tank, Dog, Tree) is for the board and pairs. The demonstrations use the study guide’s programs, all in the topic’s examples/ folder, so students who read the guide will recognize them. Open them in the IDE before class so each one is one click:

  • Day 1 demonstrations: SeatTicket, SameTicket, ShadowBug, ShadowFixed, SongPlays, ReversedThis, ThermostatRaise.
  • Day 2 demonstrations: PlayerBug, VetVisit, VisitCopyBug, RectangleCompare, StaticThisError (compile error), StaticWithParameter, MainThis (compile error), MainThisFixed, MainCallBug (compile error), MainCallFixed.
  • Printed only (exit ticket): ExitPlantCare and ExitScoreBug.

Day 1 · Warm-up: Who is “I”?

Show slide 2. Three students each say “I am first in line.” Ask: “Is the sentence true? Who does ‘I’ mean each time?” Students answer on whiteboards: the sentence is the same, but “I” means whoever is speaking, so it is true for at most one of them. Read the slide’s last line aloud: a method is the same code, run for a different object on each call. Today’s keyword is Java’s word for “I”.

Teacher note

If time allows, have three volunteers actually say the line. Hand a marker (the “microphone”) to each speaker in turn and ask the class who “I” is now. Keep it to five minutes; the point is only that the word stays the same while the speaker changes.

Day 1 · Direct instruction: This is the current object

  1. Goals (slide 3). Read the four goals; the first two are today’s and the last two are Day 2’s.
  2. What this holds (3.9.A.1, slides 4–5). Inside an instance method or a constructor, this acts as a special variable that holds a reference to the current object: the object whose method or constructor is running. Nobody declares it and nobody assigns it; Java fills it in at the start of every call with the reference before the dot. Walk through the slide 5 table: in blue.show(), this refers to blue’s object, so this.owner is "Max"; in red.show() the same line finds "Ivy". Run SeatTicket (prints Seat K9 then Seat A1): one method, two calls, two current objects.
  3. Plain names mean this. Point at the Badge constructor on slide 5: it writes plain owner, and that works, because inside an instance method or constructor a plain instance variable name means this.owner. Writing this. is optional until something else has the same name; that is the second half of today.
  4. Testing what this holds (slide 6). Ask students to predict both lines before you reveal the output. red.isSame(blue) is false even though both badges say "Ivy": they are two objects, and == on references asks “same object?”, not “same contents?” (Topic 2.6). blue.isSame(copy) is true because copy is an alias of blue. Name this == other as a self-referencing expression: the object compares itself with something else. Run SameTicket for a second version of the same test.
  5. Not the newest object (slide 7). Walk the three claims in the table. red was not created last, yet red.show() printed Ivy. this is decided by the call, not by the order of creation, and it is never the class itself, because a class has no single owner.

Misconception: this means the newest object, or the class

Students who watched two objects being created assume this is the most recent one, or they picture this as the class. Both fail on slide 7: the call red.show() prints Ivy, and the class has no single owner to print. Give them the one question to ask: “Which reference is before the dot in the call that is running?” Have them circle it in every trace for the rest of the topic.

Day 1 · Guided practice: Whose coins?

Show slide 8. Pairs write a call table (call, this, coins after) for the three save calls, then the output. hog.save(5) makes hog 55, pig.save(20) makes pig 30, and hog.save(1) makes hog 56, so the output is 30 then 56. Ask a pair that got 86 what they did: they added every amount to one total, treating this as one shared object.

Then pairs do worksheet question 2 (you’re the JVM). The answer is A (35 25): b.rise(5) makes b 25, and a.rise(b.getHeight()) passes 25 and adds it to a’s 10. Ask which idea each wrong choice uses: B treats this as the newest kite, C adds 5 to a, and D treats height as shared by both kites. Read the “Fair question” box together: getHeight() needs no this. because nothing else in it is named height.

Day 1 · Direct instruction: Reaching a hidden instance variable

  1. The shadowing problem (slides 9–10). Remind students of the Topic 3.8 rule: a parameter with the same name as an instance variable hides it inside the method. Show only the left side of slide 10 and ask what new Book("Lin") followed by getAuthor() prints. Run ShadowBug (prints null and 0): it compiles and runs, but title = title; copies the parameter into itself, and the instance variables keep their defaults (Topic 3.4). Say the word shadowed for the hidden instance variable.
  2. The fix. Reveal the right side of slide 10. this.author means the current object’s author; the plain author is the parameter. Inside a constructor, the current object is the one being built. Run ShadowFixed (prints Sunrise and 12).
  3. Both names in one line (slide 11). In drive(int miles), the plain miles is the parameter and this.miles is the trip’s running total, so this.miles = this.miles + miles; adds one to the other. Fill in the slide’s table with the class: 100, then 130, then 142. SongPlays shows the same pattern with addPlays.
  4. The wrong side (slide 12). Ask: “Both versions have this in them. Why does the left one print null?” Assignment copies from right to left (Topic 1.4), so the instance variable must be on the left, the side that receives the value. Run ReversedThis to show it compiles and prints null.

Misconception: this on the wrong side of the assignment

Students remember that the constructor “needs this” but not where it goes, and write author = this.author;. That reads the instance variable (still null) into the parameter, which disappears when the constructor ends. Have students read every assignment aloud as “store the right side into the left side” and ask, “Which side is the object’s variable?”

Misconception: It compiled, so the constructor worked

title = title; and author = this.author; are legal Java, so the compiler says nothing. The only symptom is a null or a 0 in the output. When a getter returns a default value right after construction, teach students to look first at the constructor’s assignments for a missing or misplaced this..

Day 1 · Guided practice: Did the tank fill up?

Show slide 13 and have each student write the two output lines before pairs compare. The answer is Now 30 then 10. Line 4 of the method begins with int, so it declares a new local variable named fuel; its right side reads this.fuel (10) and adds 20. The print shows the local 30, but the local variable disappears when refill ends and the instance variable was never assigned, so getFuel() returns 10. Ask for the fix: this.fuel = this.fuel + amt; (or this.fuel += amt;). ThermostatRaise is the same trap if you want a second run.

Misconception: A local variable with the same name changes the object

Students see fuel on the left of = and assume the instance variable changed. The int at the start makes it a declaration of a brand-new local variable, which shadows the instance variable for the rest of the method. Have them circle any type name at the start of an assignment: if there is one, a new variable is being made.

Day 1 · Closure: Closure

Students finish on a sticky note: “In this.miles = miles;, the left side is __ and the right side is __.” Look for “the current object’s instance variable” and “the parameter”. Assign worksheet questions 1 (face-off) and 3 (match-up) for homework.

Teacher note

Question 3’s matches: version 1 prints S (Sunrise 12), version 2 prints R (null 12), version 3 prints Q (Sunrise 0), and version 4 prints P (null 0). Version 4 is the slide 12 mistake on both lines. Question 1’s last line (“this == other is true only when we’re the same object”) previews slide 6 again.

Day 2 · Warm-up: The player with no name

Show PlayerBug without running it. It is meant to print Zara is at level 3. Students write what it actually prints and which line causes it. It prints null is at level 3: line 8, name = name;, copies the parameter into itself, while line 9 correctly uses this.level. Fix it to this.name = name; and run it. Use the minute that is left to check the Day 1 homework answers for question 3.

Day 2 · Direct instruction: Passing this along

  1. Pass this to share the current object (3.9.A.2, slides 14–15). Inside visit, the dog does not know what main named it; it has no variable called rex. What it does have is this. g.groom(this) passes a reference to the current dog. Recall Topic 3.6: passing a reference copies the reference, not the object, so the groomer’s d refers to rex’s object, and d.wash() changes it. The output is true.
  2. Trace the nesting with VetVisit. Run it (Dr. Ortiz examines Rex, true, false) and draw the chain on the board: in visit, this is the pet; in examine, this is the vet and patient is the pet; in markHealthy, this is the pet again. Each method gets its own this, set by its own call.
  3. A new object is not this. Show VisitCopyBug, which passes new Pet(name) instead of this. Ask students to predict, then run it: the vet prints the right name, but rex.isHealthy() is false, because the vet changed an object nobody keeps.
  4. Ask the other object, and pass yourself (slide 16). fir.shorter(oak) calls oak.taller(fir): the roles swap, so the old other becomes the new this. oak is 30 and fir is 18, so the output is true then false. RectangleCompare is the guide’s version (true, false).

Misconception: Passing this sends a copy of the object

Students think c.cheer(this) hands the coach a duplicate, so changes made through the parameter cannot reach the original. this holds a reference; the parameter receives a copy of that reference, which refers to the very same object. Point to the VetVisit output: rex.isHealthy() printed true. This is the lie in worksheet question 6.

Misconception: Building a new object instead of passing this

Students who do not trust this write doctor.examine(new Pet(name)). It compiles, and the printed name even looks right, but the change lands on a throwaway object. To let another method act on the current object, pass this.

Day 2 · Guided practice: Snippet pool

Pairs do worksheet question 4 (snippet pool). The holes are (1) this.name, (2) this, and (3) winner.name. Cold-call a pair for each hole and ask why the decoy fails: name = name; in the constructor leaves null; passing loser in beat prints Owls lost to Owls; plain name in hole 3 would print the loser’s own name, because inside lostTo, this is the loser.

Day 2 · Direct instruction: Class methods have no this

  1. No current object, no this (3.9.A.3, slides 17–18). Ask the Day 1 question about Tree.getHeight(): which object is before the dot? None, only a class name. A class (static) method runs without a current object, so it has no this. Run StaticThisError and read the message together: non-static variable this cannot be referenced from a static context. “Static context” means “inside a class method”.
  2. Plain names fail too. A plain instance variable name means this.height, and an instance method call with no dot means this.getHeight(). That is why Topic 3.7’s rule holds: a class method cannot use instance variables or call instance methods directly.
  3. main is static too (slide 18, right side). Run MainThis (compile error), then MainThisFixed, which calls the method on the object main created: game.getScore() prints 40. MainCallBug and MainCallFixed show the same error for a plain call, printScore();.
  4. What a class method can do. Run StaticWithParameter (3, true, false, K9). The class method sameRow reaches tickets only through its parameters, first.seat and second.seat. The fix for a static method that wants an object is either to remove static or to pass the object in.

Misconception: this works in main because main is inside the class

Students write this.getScore() in main because main sits inside the class whose objects it makes. main is static, so it has no current object; it runs before any object exists. The fix is to use the variable that holds the object: game.getScore().

Misconception: A class method can use this once an object exists

Students reason that after new Tree(30) there is an object for this to mean. Ask: “If there were three trees, which one would Tree.getHeight() mean?” A class method has no this no matter how many objects exist, and giving it a parameter does not create one either; it uses the parameter’s name instead.

Day 2 · Guided practice: Which methods compile?

Show slide 19. Students vote with fingers (one finger per method that compiles), then justify. A and C compile: A is an instance method, so it has a this, and C is a class method that reaches the tree through its parameter t (allowed to use the private height because it is inside Tree, Topic 3.6). B and D do not: both are static and use this. Then students start worksheet question 5 (you’re the compiler) alone; rows 1, 3, and 6 do not compile, and rows 2, 4, and 5 do.

Teacher note

Row 3 of question 5 (return getHour() > 12; in a static method) is the one students miss: the call has no this written, but it still means this.getHour(). Check it before students take the rest of the question home. Questions 6, 7, and 8 are homework. In question 7, the only fix is line 8, this.volume = volume;; adding this. anywhere else still prints 3.

Day 2 · Closure: Closure and exit ticket

Show slide 20 for the vocabulary and run slide 21 as a 90-second pair-share with its sentence starter: “this refers to __. A static method has no this because __.” Listen for “the object before the dot” and “there is no current object”. Then give the exit ticket (about five minutes). Score each question separately: question 1 checks what this refers to and passing this (3.9.A.1, 3.9.A.2), question 2 the shadowing fix, and question 3 class methods (3.9.A.3). This is the last topic in Unit 3, so re-teach the weakest one during unit review.

Exit ticket

Question 1 · Multiple choice

What does this program print?

class Gardener
{
    public void care(Plant p)
    {
        p.addWater(5);
    }
}

class Plant
{
    private String name;
    private int water;

    public Plant(String name, int water)
    {
        this.name = name;
        this.water = water;
    }

    public void askFor(Gardener g)
    {
        g.care(this);
    }

    public void addWater(int water)
    {
        this.water = this.water + water;
    }

    public String report()
    {
        return name + " " + water;
    }
}

public class ExitPlantCare
{
    public static void main(String[] args)
    {
        Plant fern = new Plant("Fern", 2);
        Plant cactus = new Plant("Cactus", 1);
        Gardener sam = new Gardener();
        cactus.askFor(sam);
        fern.addWater(3);
        cactus.askFor(sam);
        System.out.println(fern.report());
        System.out.println(cactus.report());
    }
}
  1. Fern 5, then Cactus 1 on the next line
  2. Fern 6, then Cactus 10 on the next line
  3. Fern 4, then Cactus 4 on the next line
  4. Fern 5, then Cactus 11 on the next line
Check your reasoning

D.

Call this What happens Fern Cactus
(constructors) Each new plant stores its parameters with this. 2 1
cactus.askFor(sam) Cactus g.care(this) passes Cactus; p.addWater(5) changes Cactus 2 6
fern.addWater(3) Fern this.water + water is 2 + 3 5 6
cactus.askFor(sam) Cactus Cactus is passed again and gets 5 more 5 11

this is the object before the dot in each call. In askFor, passing this hands the gardener a reference to the same plant, not a copy, so p.addWater(5) changes Cactus itself. In addWater, the parameter water shadows the instance variable, so this.water is the plant’s total and plain water is the amount.

  • A treats g.care(this) as passing a copy of the plant, so the gardener’s water never reaches Cactus.
  • B reads both names in this.water + water as the amount (3 + 3, then 5 + 5 twice), but this.water is always the instance variable.
  • C reads both names as the instance variable (2 + 2 for Fern; 1 + 1, then 2 + 2 for Cactus), but plain water is the parameter, which shadows it.

Question 2 · Multiple choice

This program is meant to print Rae: 9, but it prints Rae: 0. Which change fixes it?

class Score
{
    private String player;
    private int points;

    public Score(String player, int points)
    {
        this.player = player;
        points = points;
    }

    public String report()
    {
        return player + ": " + points;
    }
}

public class ExitScoreBug
{
    public static void main(String[] args)
    {
        Score s = new Score("Rae", 9);
        System.out.println(s.report());
    }
}
  1. Change line 9 to points = this.points;
  2. Change line 9 to this.points = points;
  3. Change line 14 to return player + ": " + this.points;
  4. Delete line 9; the parameter has the same name as the instance variable, so it sets it automatically.
Check your reasoning

B. Inside the constructor, the parameter points shadows the instance variable points, so both names on line 9 mean the parameter, and it is copied into itself. The instance variable is never assigned and keeps its default, 0. With this.points on the left, the parameter’s 9 is stored in the instance variable, the same way line 8 stores the name.

  • A puts this. on the wrong side: it copies the object’s 0 into the parameter and still prints Rae: 0.
  • C changes the wrong line. In report there is no parameter named points, so points already means the instance variable; the program still prints Rae: 0.
  • D removes the only line that could store the 9. A matching name does not connect a parameter to an instance variable; the program still prints Rae: 0.

Question 3 · Multiple choice

A class Locker has the instance variable private int code;. Which method compiles when it is added to Locker?

  1. public static int peek() { return this.code; }
  2. public static void reset() { code = 0; }
  3. public static boolean match(Locker a, Locker b) { return a.code == b.code; }
  4. public static void copyTo(Locker other) { other.code = this.code; }
Check your reasoning

C. A class (static) method has no current object, so it has no this, but it may work with objects passed to it as parameters. a.code and b.code are allowed even though code is private, because a and b are Lockers and the method is inside Locker.

  • A does not compile: a static method has no this (non-static variable this cannot be referenced from a static context).
  • B does not compile: the plain name code means this.code, and there is no this.
  • D does not compile: other.code is fine, but this.code is not. Having a parameter does not give a static method a current object.