How to create an immutable class in Java?
- Declare the class
final(no subclass can break it). - Make all fields
private final. - Do not write setters.
- Set all fields in the constructor.
- For mutable fields (like a list or a date) make a defensive copy when you get it and when you return it.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
static final class Team {
private final String name;
private final List<String> members;
Team(String name, List<String> members) {
this.name = name;
this.members = List.copyOf(members); // copy in
}
String name() { return name; }
List<String> members() { return members; } // List.copyOf is already unmodifiable
}
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Riya", "Aman"));
Team t = new Team("Java", list);
list.add("Hacker"); // does not change the team
System.out.println(t.members());
try {
t.members().add("Another");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot change the members");
}
}
}
Output
[Riya, Aman]
Cannot change the members
A record is the shortest way, if you only need the data and you copy the mutable parts yourself. See Java Records.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |