How do you create an immutable class in Java?
Make the class final, all fields private and final, set them only in the constructor, add no setters, and copy any mutable object on the way in and on the way out.
Explain it simply
An immutable object is like a printed marksheet: once issued, nobody edits it. If something changes, a new sheet is issued. This makes the object safe to share between threads and to use as a map key, because its state can never shift under you.
The tricky part is mutable fields such as Date or List. If you store the caller's list directly, the caller can still change it later.
Example
public final class Batch {
private final String name;
private final List<String> students;
public Batch(String name, List<String> students) {
this.name = name;
this.students = new ArrayList<>(students); // defensive copy in
}
public String getName() { return name; }
public List<String> getStudents() {
return Collections.unmodifiableList(students); // safe view out
}
}String itself is the best-known immutable class. Java records (record Batch(String name)) give shallow immutability with less code.
What to say in the interview
"I declare the class final, make fields private final, initialise them in the constructor, provide no setters, and make defensive copies of mutable inputs and outputs. Immutable objects are thread-safe, cache-friendly and safe as hash keys."
Common mistakes
- Making fields final but exposing the internal List through a getter.
- Forgetting to make the class final, so a subclass can add mutable state.