ACSA Exam Prep
Unit 3 · Class Creation · Topic 3.6

Methods: Passing and Returning References of an Object

Skill 2.CSkill 4.A

Big idea: Passing an object passes a copy of the reference, so the method can change the caller's object, but reassigning the parameter has no effect outside.

Learning objectives
  • Develop code to define behaviors of an object through methods written in a class using object references and determine the result of calling these methods.

Changing the object vs. reassigning the parameter

addBonus uses its copy of the reference to change the shared object, so the caller sees the change. replace points its own copy at a new object; the caller's variable still refers to the original.

Methods
static void addBonus(BankAccount acct) { acct.deposit(10); }
static void replace(BankAccount acct) { acct = new BankAccount("New", 0); }
Using them
BankAccount a = new BankAccount("Lee", 100.0);
addBonus(a);
System.out.println(a.getBalance());
replace(a);
System.out.println(a.getBalance());
Output
110.0
110.0

Returning a reference

Returning an object returns its reference, not a copy. The caller then shares that object.

Methods
static BankAccount richer(BankAccount x, BankAccount y) {
  if (x.getBalance() >= y.getBalance()) return x;
  return y;
}
Using them
BankAccount rich = richer(new BankAccount("A", 5), new BankAccount("B", 9));
System.out.println(rich.getBalance());
Output
9.0

Private access for the same class

A method can use the private data of a parameter only when the parameter's type is the method's own class. This is common in equals-style methods.

public boolean sameOwner(BankAccount other) {
  return owner.equals(other.owner);   // legal: other is also a BankAccount
}
Key points
  • A reference parameter gets a copy of the reference; the method can change the shared object's state.
  • Reassigning a reference parameter never affects the caller.
  • Returning an object returns its reference.
  • Good practice: don't modify a mutable parameter unless the specification says to.
Watch out
  • Draw boxes and arrows: the variable box holds an arrow, the object is a separate box.
Quick check
A method sets arr[0] = 99 on an array parameter. Does the caller's array change?
Show answer
Yes. The parameter and the caller's variable refer to the same array object.