Interview Q&A / Object-Oriented Programming

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How do you create an immutable class in Java?

SHORT ANSWER

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

java
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.

#immutability#java#design

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.