Immutable classes are classes whose objects cannot be modified after they are created. Once an instance of an immutable class is initialized, its state cannot be changed. This property makes immutable objects particularly useful in concurrent programming because they ensure thread safety without requiring synchronization. Their instances are also ideal for use as keys in hash-based collections like HashMap
because their hash code is constant.
How to create an Immutable Class in Java
- Declare the class as
final
to prevent subclassing. - Mark all fields as
final
. This will ensure that they can only be assigned once, typically in the constructor. - Do not have setter methods or any methods that modify fields
- If the class contains fields that refer to mutable objects, return copies of these objects rather than the original reference.
Code Example
public final class ImmutableBook {
private final String name;
private final String author;
private final String isbn;
// Constructor
public ImmutableBook(String name, String author, String isbn) {
this.name = name;
this.author = author;
this.isbn = isbn;
}
// Getter methods
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public String getIsbn() {
return isbn;
}
}