SteelReed

Search

Search posts, questions…

Java CoreQuestion 21 / 43

Middle

How do you write an immutable class? Is a record fully immutable?

Short answer

An immutable class can't change once created: private final fields, no setters, a final class, and copies of changeable fields like List.

List.copyOf in constructorcaller edits original listwithItemCaller passes a Listprivate final fieldObject unchangedGetter returnsunmodifiable listReturns new object

3 points to say:

  1. To "change" it, return a new object (withX).
  2. Threads can share it without locks.
  3. A record still needs List.copyOf for a list inside.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.