Unit 3 Cycle 2 Day 24: Encapsulation: Returning Mutable References
Share
Encapsulation: Returning Mutable References
Section 3.4 — Accessor Methods
Key Concept
Returning a reference to a mutable private field breaks encapsulation because the caller can modify the object's internal state without going through a mutator. For example, if getList() returns the actual ArrayList field, the caller can add or remove elements directly. The defensive copy pattern returns new ArrayList<>(this.list) instead. The AP exam tests this concept by asking whether external code can unexpectedly modify an object's state through a returned reference.
Consider the following class.
What is the potential problem with this design?
Answer: (D) Both B and C are problems.
Both the constructor and getter expose the internal array reference. External code can modify names via the constructor argument or the returned array. Both should return/store copies to maintain encapsulation.
Why Not the Others?
(A) An accessor returning data is correct. The problem is returning a mutable reference.
(B) Correct but incomplete. The constructor also has the same problem.
(C) Correct but incomplete. The getter also has the problem.
Common Mistake
Returning a reference to a mutable object (like an array) breaks encapsulation. External code can modify the array without going through the class methods. Store and return copies instead.
AP Exam Tip
Defensive copying: store a copy in the constructor and return a copy from getters when dealing with mutable types like arrays and ArrayLists.