Junior
What are immutable classes in Java?
sobes.tech AI
Answer from AI
An immutable class in Java is a class whose objects cannot be changed after creation.
Rules for creating an immutable class:
- The class should be declared as
finalto prevent inheritance and modification of behavior by subclasses. - All fields should be declared as
finalso they cannot be changed after initialization. - All fields should be declared as
privateto prevent direct access from outside. - Do not provide setter methods.
- If the class contains mutable fields, such as
List, they should be copied in the constructor and when returned from getter methods (defensive copy). - Do not provide methods that can change the state of the object.
Advantages of immutable classes:
- Thread safety: multiple threads can safely access the same object without synchronization.
- Caching: immutable objects are easy to cache, improving performance.
- Ease of debugging and testing: the state of the object is predictable.
- Use as keys in associative collections (
Map,Set).
Example of an immutable class:
final class ImmutableExample {
private final String name;
private final int value;
private final List<String> tags;
public ImmutableExample(String name, int value, List<String> tags) {
this.name = name; // Primitives and String are immutable
this.value = value;
// Defensive copying of mutable field in constructor
this.tags = new ArrayList<>(tags);
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public List<String> getTags() {
// Defensive copying when returning mutable field
return new ArrayList<>(tags);
}
// No setters or methods that change state
}