Defensive Copying in Getters and Setters
You'll learn how to protect your class's internal mutable objects from unwanted external modification.
When a field holds a reference to a mutable object (like an array or Date), simply returning that reference in a getter creates a security hole. The caller can then modify the object, bypassing your class's encapsulation and validation logic.
Think of it like this: If you're a museum curator showing off a priceless painting, you don't hand visitors the original—you show them a photograph. If they scribble on the photo, your original stays safe.
The Problem
public class Student {
private int[] grades;
public Student(int[] grades) {
this.grades = grades; // DANGER: stores external reference
}
public int[] getGrades() {
return grades; // DANGER: exposes internal reference
}
}
A caller can now corrupt the internal state:
Student student = new Student(new int[]{85, 90, 92});
int[] leaked = student.getGrades();
leaked[0] = 0; // Oops! Just changed the student's grade internally
The Solution: Defensive Copying
In the setter (or constructor): Store a copy of the incoming object.
public Student(int[] grades) {
this.grades = Arrays.copyOf(grades, grades.length); // Store a copy
}
In the getter: Return a copy of the internal object.
public int[] getGrades() {
return Arrays.copyOf(grades, grades.length); // Return a copy
}
Now external code can only modify their copy, not your internal state.
Key Takeaway: Always use defensive copying for mutable object fields—copy incoming data in setters/constructors and return copies in getters to maintain true encapsulation.