Skip to content

Course navigation

For teachersTopic 3.6 · Lesson kit

Methods: Passing and Returning References of an Object

  • 2 class periods
  • 45 minutes each
  • Objective 3.6.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.6.A
Essential knowledge
3.6.A.13.6.A.23.6.A.3
Materials
Projector and the Same Bucket slide deckWhiteboard and markersMini whiteboards or scrap paperIDE on the projector (optional demonstrations)Printed Same Bucket puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-uptwo sticky notes, one house (slide 2)
  2. 0:05–0:2015 minDirect instructionthe parameter gets a copy of the reference (slides 3–7)
  3. 0:20–0:277 minGuided practiceload, then let go (slide 8)
  4. 0:27–0:3710 minDirect instructionspecifications, side effects, String (slides 9–11)
  5. 0:37–0:425 minIndependent practicepuzzle worksheet question 1
  6. 0:42–0:453 minClosurechange it, or point elsewhere?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upworksheet question 1, last row
  2. 0:05–0:1712 minDirect instructionreturning a reference, the leaky getter (slides 12–14)
  3. 0:17–0:236 minGuided practicefollow the returns (slide 15)
  4. 0:23–0:3310 minDirect instructionprivate data of a parameter (slides 16–17)
  5. 0:33–0:374 minGuided practicewhich line compiles in Cashier? (slide 18)
  6. 0:37–0:403 minClosurevocabulary and sentence starter (slides 19–20)
  7. 0:40–0:455 minExit ticket

Overview

Topic 3.6 has one learning objective (3.6.A) and three ideas. Day 1 is passing: when the argument is an object, the parameter gets a copy of the reference, not a copy of the object, so a method can change a mutable object through its parameter, but assigning the parameter a new object changes nothing for the caller; and a method should not change an object passed to it unless its specification says to (3.6.A.1). Day 2 is returning a reference, not a copy (3.6.A.2), and the rule that a method may use a parameter’s private data and methods only when the parameter’s type is the method’s own class (3.6.A.3).

Keep one question running through both days: “Which object does this variable lead to?” Every trace in the topic is answered by following references, and the only way to get a second object is new.

Students know references, aliases, and null (Topics 1.13, 2.6), immutable Strings (Topic 1.15), private (Topic 3.3), constructors (Topic 3.4), and writing methods with primitive parameters, accessors, and mutators (Topic 3.5). Stay inside the topic boundary: methods students write are instance methods called on an object (shop.addBonus(card)); static methods of their own wait for Topic 3.7, scope rules for Topic 3.8, and this for Topic 3.9. No arrays or ArrayList.

Teacher note

The slides are the Same Bucket deck (20 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–11 and Day 2 uses slides 12–20. The deck’s running class is Card (a gift card with a private name and balance, and a mutator load); the worksheet’s is Bucket (color, liters, mutator add); the study guide’s is Player. Point out that it is the same pattern each time: one mutable class, plus a second class whose methods receive it.

The Same Bucket puzzle worksheet (9 questions, about 30 minutes) is split across the two nights: questions 1, 6, 7, and 8 after Day 1; questions 2, 3, 4, 5, and 9 after Day 2.

Optional IDE demonstrations, all in the topic’s examples/ folder (each file is a complete program with its own Player class): Day 1: BonusByReference, BonusByValue, ReplaceParameter, SwapPlayersWrong, CheerString, PreviewChanges, WelcomeBonus. Day 2: LeaderReturn, CaptainLeak, FakeCopy, AheadOf, BothScored, PrivateFromOutside, TradeDay. Printed only (exit ticket): ExitJar.

Day 1 · Warm-up: Two sticky notes, one house

Show slide 2. Pairs get two minutes for the two situations. Situation 1: yes, your house is blue, because both notes held the address of one house. Situation 2: no, your note does not change; your friend changed only their own note, and yours still leads to your house. Tell students to remember both answers: today Java does exactly this, and the two situations are the two halves of the lesson.

Day 1 · Direct instruction: The parameter gets a copy of the reference

  1. Goals (slide 3). Goals 1–3 are Day 1; goals 4 and 5 are Day 2.
  2. Copy the reference, not the object (slide 5; 3.6.A.1). Recall Topic 3.5: a parameter is initialized with a copy of its argument. A variable such as card holds a reference, so the parameter c gets a copy of that reference. No new Card is built, because only new builds one. While the method runs, card and c are aliases (Topic 2.6). Draw the slide’s picture on the board: two variable boxes, two arrows, one object.
  3. A mutator call through the parameter (slide 6). Before revealing the output, ask: “Does main print 20 or 25?” Walk the four numbered steps: c.load(5) follows the arrow to the one shared Card, so main prints 25. Name the word: Card is mutable, because load changes its state after it is built.
  4. Contrast with a primitive. Optionally run BonusByReference and then BonusByValue: the same bonus sticks for a Player and does not stick for an int. In both cases Java copies what the argument variable holds; the difference is that one holds a number and the other holds an address.
  5. Pointing the parameter elsewhere (slide 7). c = new Card("New", 100) builds a second card and moves only c. The method prints 100; main prints 20. Connect it to the warm-up: this is Situation 2, crossing out your own sticky note. On the board, put the two statements side by side: c.load(5); (dot: go to the object and act on it) and c = …; (assignment: put a different address in c). Only the dot reaches the caller’s object.

Misconception: The method gets its own copy of the object

Students picture the call as handing the method a photocopy of the card, so they predict 20 on slide 6. Ask, “Where is the new?” Making an object always takes new (Topic 1.13), and the call has none, so there is one object and two variables. Have students draw the arrows for every trace today. This is the Think First prediction before worksheet question 1.

Misconception: Assigning to the parameter changes the caller's variable

The opposite error: once students accept that the method can change the object, they think it can do anything, including make card refer to a new object. The parameter is a separate variable that holds a copy of the address. Assigning it changes only the copy, as on slide 7. Run SwapPlayersWrong to show the consequence: swapping two parameters with temp swaps nothing in main. Worksheet question 7 (claim 3 is the lie) returns to this.

Day 1 · Guided practice: Load, then let go

Show slide 8. Students write the output and one sentence of why on mini whiteboards, then reveal together. The answer is 25: c.load(10) runs while c still refers to Ana’s card, so her balance goes from 15 to 25. Then c is pointed at a new Temp card, and c.load(50) changes only that card, which is lost when the method ends.

Ask the two wrong answers out loud and diagnose them: 15 (thinks the method never touches the caller’s card) and 75 (thinks the reassignment changed nothing and both loads hit Ana’s card). If time allows, show MixedUpdate from the guide, which is the same pattern with a Player.

Teacher note

Insist on the arrow drawing for slide 8: draw Ana’s card, then after line 2 of process draw the second card and move only the c arrow. Students who skip the picture are the ones who answer 75.

Day 1 · Direct instruction: Specifications, side effects, String

  1. Follow the specification (slides 9–10; 3.6.A.1). A method’s specification is what it is supposed to do; callers rely on it instead of reading the code. Read the slide 10 specification aloud, then have students predict all four lines of output before revealing them: 12, 20, 12, 12. Both methods return the right number, but leftBad also spent the money. A change to an object passed in that the specification did not ask for is a side effect. The compiler never complains; only the specification catches it.
  2. The rule. Do not modify a mutable object passed as a parameter unless the specification requires it. Read it with accessors instead. The rule covers constructors too: show WelcomeBonus, where a Team constructor specified only to record the captain’s name also adds points to the Player it receives.
  3. When changing it is correct. Ask: “Is addBonus on slide 6 breaking the rule?” No: adding a bonus is its job. The rule depends on the specification, not on whether the method calls a mutator.
  4. A String can’t be changed at all (slide 11). The parameter s gets a copy of word’s reference, but a String is immutable: no method changes its characters. s = s + "!" builds a new String and moves only s, which is the slide 7 case again. main prints main: hi.

Misconception: A preview method may change the object, as long as it returns the right number

Students write “add the bonus, then get the total” because that is how they would work it on paper. The first call looks right; the bug appears on the second call, somewhere else in the program. Show PreviewChanges: the same preview prints 15 and then 20. The fix computes with an accessor: return p.getPoints() + bonus;. Worksheet question 6 tests this, including choice C, where Bucket c = b; looks like a safe copy but is only an alias.

Misconception: A method can add to my String

Students know s = s + "!" changes s, so they expect the caller to see it. Two facts work together: a String has no mutators, and assigning a parameter never changes the caller’s variable. The way to get new text back is to return it, which is what String methods such as substring do. The Fair Question after worksheet question 3 answers this.

Day 1 · Independent practice: Independent practice

Students start puzzle worksheet question 1 (pencil check: fill, swapOut, fillCopy) in class; it uses only today’s ideas. Questions 6 (spec check), 7 (two truths and a lie: the failed swap), and 8 (the Parameter and Object face-off) are homework, with anything left of question 1. Before they start, read the Bucket class on page 1 together: add is its mutator.

Day 1 · Closure: Closure

Ask: “A method receives your object. Name one thing it can do that you will see, and one thing it can do that you will not see.” Listen for: calling a mutator through the parameter (you see it), and assigning the parameter a new object (you don’t).

Day 2 · Warm-up: Worksheet question 1, last row

Write the last row of worksheet question 1 on the board: g.fill(blue); then g.swapOut(blue);, starting from 4 liters. Students answer on mini whiteboards: 10. fill changed the shared bucket; swapOut moved only its own parameter. Collect answers to questions 6 and 7 with a show of fingers (6 is B; the lie in 7 is claim 3) and re-teach from slide 7 if many students missed either.

Day 2 · Direct instruction: Returning a reference, the leaky getter

  1. Return hands back the same object (slides 12–13; 3.6.A.2). Return works like passing: the return expression evaluates to a reference, and the reference is what comes back. topUp returns c, which holds kai’s address, so same is another alias: same == kai is true, and kai’s balance is 25. Point at the slide’s reminder: only new makes a copy.
  2. Returning a private object (slide 14). Cover the right side first. card is private, but getCard returns its reference, so stolen is an alias of the wallet’s own card. stolen.load(-20) empties it, and asking again shows 0. Ask: “Private was supposed to protect it. What went wrong?” private stops other classes from naming the variable; it does not protect the object once its address is handed out. Reveal the fix: return new Card(card.getName(), card.getBalance()), and the output is 20.
  3. Optional demos. LeaderReturn returns one of two parameters (the caller gets an alias of a player that already exists), and CaptainLeak is the slide 14 leak with a Player. This is the return-side partner of the Topic 3.4 advice to store a copy of a mutable object a constructor receives.

Misconception: return hands back a copy

Students think the variable that receives a returned object holds “the answer,” safe to change. Unless the method built the object with new, it is an alias of an existing one. Show FakeCopy: a makeCopy method that assigns its parameter to a local variable and returns it gives main an alias, not a backup. Ask, “Where is the new?” Worksheet question 5 (answer B, 11 false) and question 2 (the decoy return new Bucket("red", 7);) both test this.

Day 2 · Guided practice: Follow the returns

Show slide 15. Students answer both parts on mini whiteboards: it prints 20, then true, and there is one Card object. topUp(a, 5) loads Ana’s card to 15 and returns the same reference, so b is an alias of a; topUp(b, 5) loads the same card to 20 and returns it again. One card, three names (a, b, c). Students who answer “three cards” are still picturing return as a copy: ask them to find a new in topUp.

Day 2 · Direct instruction: Private data of a parameter

  1. Same class? You may look inside (slides 16–17; 3.6.A.3). private restricts access to the declaring class, not to the object. beats is written inside Card and other is a Card, so other.balance is allowed; with Kai at 20 and Mo at 35, kai.beats(mo) prints false. total is written in Cashier, so a.balance does not compile: balance has private access in Card. Outside Card, use the accessors.
  2. Why the line is drawn at the class. Code inside Card is already part of its hidden design: whoever writes Card keeps balance correct for every card. Code in Cashier is outside, so it goes through public methods. The same rule covers private methods (the guide’s BothScored).
  3. Optional demo. Run AheadOf (allowed) and then PrivateFromOutside (the compiler error). Change the failing line to return p.getPoints(); and run it again.

Misconception: An object's private data is private even from other objects of its class

Students think each object guards its own data from every other object, so they reject other.balance inside Card. private is about which class the code is written in. Worksheet question 4, item 1 (holdsMore in Bucket), compiles and prints true.

Misconception: Holding a reference means I can read its private data

The opposite error: Cashier has a perfectly good reference to a Card, so students expect a.balance to work. A reference lets you call the object’s public methods, nothing more, unless your code is inside the object’s class. Worksheet question 3, hole (1) (from.liters is a trap), and question 4, item 2, test this.

Day 2 · Guided practice: Which line compiles in Cashier?

Show slide 18. Students hold up A, B, C, or D. The answer is B only: Cashier is not Card, so it cannot read or write a.balance (A, C) or a.name (D), even just to read. Each choice was compiled inside a Cashier method, and javac rejects A, C, and D with “has private access in Card”. Ask: “Which of these would compile if the method were written inside Card?” All four.

Day 2 · Independent practice: Independent practice

Puzzle worksheet questions 2, 3, 4, 5, and 9 are homework: the code tiles (bigger returns the bucket itself), the snippet pool (pourAll, which must use the accessor and return to), you’re the compiler (private access and return types), copy or leak (getSpare against copySpare), and who am I. Students who finish early can start in class.

Day 2 · Closure: Closure and exit ticket

Show slide 19 and point to each word, asking for a line of code from the two days that shows it (for example, card and c on slide 6 for alias, load for mutable, leftBad for side effect). Then slide 20: pairs finish the sentence starter (“a copy of the reference, so calling a mutator through it changes my object, but assigning it a new object doesn’t”).

Give the exit ticket (about five minutes). Question 1 checks passing and returning references (3.6.A.1, 3.6.A.2), question 2 checks private access through a parameter (3.6.A.3), and question 3 checks the specification rule (3.6.A.1). Re-teach the weakest one at the start of Topic 3.7, which builds on 3.6.A.3: a class method can use instance data only through an object passed as a parameter.

Exit ticket

Question 1 · Multiple choice

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

ExitJar.java
public class ExitJar
{
    public static void main(String[] args)
    {
        Jar mine = new Jar(10);
        Helper h = new Helper();
        Jar back = h.change(mine);
        System.out.println(mine.getCoins());
        System.out.println(back.getCoins());
        System.out.println(back == mine);
    }
}

class Helper
{
    public Jar change(Jar j)
    {
        j.addCoins(5);
        j = new Jar(1);
        j.addCoins(5);
        return j;
    }
}

class Jar
{
    private int coins;

    public Jar(int start)
    {
        coins = start;
    }

    public int getCoins()
    {
        return coins;
    }

    public void addCoins(int amount)
    {
        coins = coins + amount;
    }
}
  1. 10, 6, false
  2. 6, 6, true
  3. 20, 20, true
  4. 15, 6, false
Check your reasoning

D. Line 7 copies mine’s reference into j, so j and mine refer to the same jar. Line 18 adds 5 through j, so that jar has 15. Line 19 points j at a new jar holding 1; mine still refers to the first jar. Line 20 adds 5 to the new jar (6), and line 21 returns the new jar’s reference, which is stored in back. So mine has 15, back has 6, and back == mine is false because they refer to different objects.

  • A thinks the method gets its own copy of the jar, so line 18 does not change mine’s jar. It gets a copy of the reference, not of the object.
  • B thinks line 19 changes mine too, so mine now refers to the new jar. Assigning to the parameter changes only j.
  • C ignores line 19 and keeps adding to mine’s jar, so the method returns the jar it was passed.

Question 2 · Multiple choice

Helper and Jar are the classes in question 1. Which method compiles when it is added to the class named?

  1. In Helper: public int total(Jar a, Jar b) { return a.coins + b.coins; }
  2. In Jar: public boolean hasMore(Jar other) { return coins > other.coins; }
  3. In Helper: public void empty(Jar j) { j.coins = 0; }
  4. In Helper: public Jar pick(Jar j) { return j.getCoins(); }
Check your reasoning

B. hasMore is written inside Jar, and its parameter is a Jar, so it may use other.coins even though coins is private. A and C are in Helper, a different class, so a.coins, b.coins, and j.coins do not compile (coins has private access in Jar), whether the code reads the variable or assigns it; Helper must use getCoins and addCoins. D uses only a public accessor, but it returns an int where the return type is Jar, so it does not compile.

Question 3 · Multiple choice

The specification of a Helper method public int afterSpending(Jar j, int cost) says: “Returns how many coins j would have left after spending cost. Does not change j.” A student writes the body j.addCoins(-cost); return j.getCoins();. The returned number is correct. Which statement about the method is true?

  1. It breaks the specification: j refers to the caller’s jar, so j.addCoins(-cost) really spends the caller’s coins. A correct body is return j.getCoins() - cost;.
  2. Nothing is wrong: j is a copy, so changes made through it do not reach the caller’s jar.
  3. Nothing is wrong: the specification only describes the method, and the returned number is what matters.
  4. It breaks the specification. A correct body reads the variable directly: return j.coins - cost;.
Check your reasoning

A. j holds a copy of the caller’s reference, so it refers to the same jar, and addCoins changes that jar: a side effect the specification says not to have. It is good practice not to change an object passed as a parameter unless the specification requires it. return j.getCoins() - cost; only reads the jar.

  • B confuses a copy of the reference with a copy of the object. There is only one jar.
  • C ignores the specification. Code that calls afterSpending trusts it, so its jar losing coins is a bug even when the returned number is right.
  • D finds the problem, but the fix does not compile: afterSpending is in Helper, and coins is private to Jar (coins has private access in Jar).