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.
- 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.
static void addBonus(BankAccount acct) { acct.deposit(10); }
static void replace(BankAccount acct) { acct = new BankAccount("New", 0); }Using themBankAccount a = new BankAccount("Lee", 100.0);
addBonus(a);
System.out.println(a.getBalance());
replace(a);
System.out.println(a.getBalance());Output110.0 110.0
Returning a reference
Returning an object returns its reference, not a copy. The caller then shares that object.
Methodsstatic BankAccount richer(BankAccount x, BankAccount y) {
if (x.getBalance() >= y.getBalance()) return x;
return y;
}Using themBankAccount rich = richer(new BankAccount("A", 5), new BankAccount("B", 9));
System.out.println(rich.getBalance());Output9.0Private 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
}- 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.
- Draw boxes and arrows: the variable box holds an arrow, the object is a separate box.
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.