Middle
How to write an immutable class in Java?
sobes.tech AI
Answer from AI
To make a class immutable in Java, follow these principles:
- Make the class
finalso it cannot be subclassed and its behavior cannot be changed. - Make all class fields
privateandfinalso they cannot be modified after object initialization. - Do not provide setter methods.
- If the class contains mutable fields (e.g.,
ListorDate), return copies of these objects in getters instead of references to the original objects. Also, accept copies of mutable objects in the constructor. - Override
equals()andhashCode()methods if necessary for correct object comparison and collection operations.
Example:
// Final class to prevent inheritance
public final class ImmutablePerson {
// Private final fields
private final String name;
private final int age;
private final List<String> achievements;
// Constructor initializing all fields.
// Creates copies of mutable fields.
public ImmutablePerson(String name, int age, List<String> achievements) {
this.name = name;
this.age = age;
// Creating a copy of the mutable list
this.achievements = new ArrayList<>(achievements);
}
// Getters returning field values.
// Return copies for mutable fields.
public String getName() {
return name;
}
public int getAge() {
return age;
}
public List<String> getAchievements() {
// Return a copy of the list to prevent external modification
return new ArrayList<>(achievements);
}
// Override equals and hashCode (optional but often necessary)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImmutablePerson that = (ImmutablePerson) o;
return age == that.age &&
Objects.equals(name, that.name) &&
Objects.equals(achievements, that.achievements);
}
@Override
public int hashCode() {
return Objects.hash(name, age, achievements);
}
}
This class guarantees that once an object is created, its state (field values) cannot be changed. This provides advantages in multithreading, security, and simplifies development.