Immutable Classes and Records
50 min · Intermediate
An immutable object never changes after construction. Interviewers ask for the steps to write one, then look for the defensive-copy mistake, then ask how records make it shorter and where they still leak.
Topics in this lesson
- Steps to write an immutable class
- The defensive copy trap with a List or Date field
- Records as concise immutable data carriers
- Benefits asked: thread safety, safe map keys, caching
- Trap: a record with a mutable list component
Interview questions this lesson answers
- What is an immutable class?
- How do you make a class immutable?
- Why make the class itself final?
- Is making fields final enough for immutability?
- What is a record?
- What is a defensive copy?
- Where do you need defensive copies?
List.copyOfvsCollections.unmodifiableList: what is the difference?- Does
List.copyOfallow null elements? - Why is
java.util.Datea problem in an immutable class?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.