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):
ExitPlantCareandExitScoreBug.
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
- Goals (slide 3). Read the four goals; the first two are today’s and the last two are Day 2’s.
- What
thisholds (3.9.A.1, slides 4–5). Inside an instance method or a constructor,thisacts 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: inblue.show(),thisrefers toblue’s object, sothis.owneris"Max"; inred.show()the same line finds"Ivy". RunSeatTicket(printsSeat K9thenSeat A1): one method, two calls, two current objects. - Plain names mean
this.Point at theBadgeconstructor on slide 5: it writes plainowner, and that works, because inside an instance method or constructor a plain instance variable name meansthis.owner. Writingthis.is optional until something else has the same name; that is the second half of today. - Testing what
thisholds (slide 6). Ask students to predict both lines before you reveal the output.red.isSame(blue)isfalseeven though both badges say"Ivy": they are two objects, and==on references asks “same object?”, not “same contents?” (Topic 2.6).blue.isSame(copy)istruebecausecopyis an alias ofblue. Namethis == otheras a self-referencing expression: the object compares itself with something else. RunSameTicketfor a second version of the same test. - Not the newest object (slide 7). Walk the three claims in the table.
redwas not created last, yetred.show()printedIvy.thisis decided by the call, not by the order of creation, and it is never the class itself, because a class has no singleowner.
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
- 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 bygetAuthor()prints. RunShadowBug(printsnulland0): it compiles and runs, buttitle = 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. - The fix. Reveal the right side of slide 10.
this.authormeans the current object’sauthor; the plainauthoris the parameter. Inside a constructor, the current object is the one being built. RunShadowFixed(printsSunriseand12). - Both names in one line (slide 11). In
drive(int miles), the plainmilesis the parameter andthis.milesis the trip’s running total, sothis.miles = this.miles + miles;adds one to the other. Fill in the slide’s table with the class: 100, then 130, then 142.SongPlaysshows the same pattern withaddPlays. - The wrong side (slide 12). Ask: “Both versions have
thisin them. Why does the left one printnull?” Assignment copies from right to left (Topic 1.4), so the instance variable must be on the left, the side that receives the value. RunReversedThisto show it compiles and printsnull.
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
- Pass
thisto share the current object (3.9.A.2, slides 14–15). Insidevisit, the dog does not know whatmainnamed it; it has no variable calledrex. What it does have isthis.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’sdrefers torex’s object, andd.wash()changes it. The output istrue. - Trace the nesting with
VetVisit. Run it (Dr. Ortiz examines Rex,true,false) and draw the chain on the board: invisit,thisis the pet; inexamine,thisis the vet andpatientis the pet; inmarkHealthy,thisis the pet again. Each method gets its ownthis, set by its own call. - A new object is not
this. ShowVisitCopyBug, which passesnew Pet(name)instead ofthis. Ask students to predict, then run it: the vet prints the right name, butrex.isHealthy()isfalse, because the vet changed an object nobody keeps. - Ask the other object, and pass yourself (slide 16).
fir.shorter(oak)callsoak.taller(fir): the roles swap, so the oldotherbecomes the newthis.oakis 30 andfiris 18, so the output istruethenfalse.RectangleCompareis 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
- No current object, no
this(3.9.A.3, slides 17–18). Ask the Day 1 question aboutTree.getHeight(): which object is before the dot? None, only a class name. A class (static) method runs without a current object, so it has nothis. RunStaticThisErrorand read the message together:non-static variable this cannot be referenced from a static context. “Static context” means “inside a class method”. - Plain names fail too. A plain instance variable name means
this.height, and an instance method call with no dot meansthis.getHeight(). That is why Topic 3.7’s rule holds: a class method cannot use instance variables or call instance methods directly. mainis static too (slide 18, right side). RunMainThis(compile error), thenMainThisFixed, which calls the method on the objectmaincreated:game.getScore()prints40.MainCallBugandMainCallFixedshow the same error for a plain call,printScore();.- What a class method can do. Run
StaticWithParameter(3,true,false,K9). The class methodsameRowreaches tickets only through its parameters,first.seatandsecond.seat. The fix for a static method that wants an object is either to removestaticor 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.