These notes recap Topic 3.6. For explanations and worked examples, read the study guide.
Recap
- When the argument is an object reference, the parameter is initialised with a copy of the reference. No new copy of the object is made.
- If the object is mutable, a method can change its state through the reference. The caller sees the change.
- Assigning a new object to the parameter changes only the parameter. The caller’s variable is unaffected.
- When a method returns an object, it returns the reference, not a copy.
- A method cannot reach the private data of a parameter unless the parameter has the same type as the enclosing class.
- Good practice: do not modify mutable objects passed as parameters unless the specification requires it.
Key relationships
| Code inside the method | Effect on the caller’s object |
|---|---|
b.addItem(); (call a mutator on the parameter) |
Changes the shared object: caller sees it |
b = new Box(100); (reassign the parameter) |
No effect on the caller’s variable |
return a; where a is a parameter |
Returns the same object: an alias |
return new Box(a.getItems()); |
Returns an independent copy |
other.items inside class Box, other a Box |
Allowed |
b.items inside a different class |
Compile error: private access |
Reference checklist for tracing
- Draw each variable with an arrow to its object.
- At a method call, draw the parameter with an arrow to the same object.
- A call to a mutator changes the object. An assignment to the parameter moves only the parameter’s arrow.
- At
return, the returned reference points to the same object. ==asks whether two arrows point to the same object.
Worked reminder
With Box x = new Box(3): addTwo(x) makes the box hold 5, because b and x point to the same object. replace(x) leaves it at 5, because b = new Box(100) only moves b. With s at 4 items and t at 9, biggerOf(s, t) returns the reference to t’s box; after big.addItem() it holds 10 and big == t is true.
Mistakes to avoid
- Thinking a swap method that swaps its parameters swaps the caller’s variables.
- Believing a returned object is always a new object.
- Using
==when the question is about equal contents (for the objects in this topic, compare values through accessors). - Modifying a parameter object when the specification did not ask for it.
- Reading
b.itemsfrom outside the class.
Quick self-check
void f(Box b) { b = new Box(0); }is called withx. What happens tox? Answer: nothing; x still refers to the original box.Box y = x;theny.addItem();Doesxchange? Answer: Yes, they refer to the same box.- A method returns one of its two object parameters. Is the result a copy? Answer: No, it is the same object.
- May a method in class
Boxuseother.itemswhereotheris aBox? Answer: Yes.