Java · OOP, JVM and backend craft
How do you design an immutable class in Java?
Short answer
An immutable object cannot change after construction. Achieve it with final fields, no mutators, defensive copies and safe publication of any referenced mutable state.
Make the class final so a subclass cannot add mutable behaviour. Make fields private and final. Do not expose setters. If a field refers to a mutable object, copy it on the way in and on the way out, or store an unmodifiable snapshot that nobody else holds.
public final class Order {
private final String id;
private final List<String> items;
public Order(String id, List<String> items) {
this.id = id;
this.items = List.copyOf(items);
}
public List<String> items() {
return items;
}
}Where immutability leaks
- Returning a mutable internal collection lets callers change the object
- Storing a caller's mutable array or list without copying keeps an alias
- A subclass can add mutability unless the class is final or uses a private constructor
- Publishing this during construction can expose a partially built object
Records are a concise fit for shallow immutable data carriers. They generate a constructor, accessors, equals, hashCode and toString. A record only makes its fields final; any referenced mutable object still needs defensive copying.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does an immutable class need to be final?
- 2What is the difference between an unmodifiable view and a copy?
- 3Are records deeply immutable?
- 4How does immutability help with concurrency?
Say it in the interview
I make the class final, keep fields private and final, and provide no mutators. For mutable fields I copy on input and return an immutable snapshot rather than an unmodifiable view of a list I still hold. Records help with shallow value objects but do not deep-copy referenced objects. Immutable objects are safe to share across threads and are reliable map keys.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.