Creating an immutable class in Java is a common design pattern that ensures that once an object is created, its state cannot be changed. Immutable classes are useful when you want to ensure that the object’s data cannot be modified after creation, improving safety and predictability.
Steps to Create an Immutable Class in Java
- Make the class
finalto prevent subclassing, which can alter its immutability. - Make all fields
privateandfinalto ensure they cannot be modified directly. - Provide a constructor to initialize all fields. Ensure the constructor initializes the fields in such a way that they can't be modified after creation.
- Avoid setter methods to prevent modification of the fields.
- Ensure deep copying for mutable objects (like arrays or collections) to prevent external modification of internal data.
final class: The class is marked asfinalto prevent inheritance, ensuring that subclasses cannot change the immutability.private finalfields: The fieldsnameandageare marked asprivateto prevent direct access and asfinalto ensure they can only be assigned once.Constructor: The constructor initializes the fields. Once a
Personobject is created, its state (thenameandage) cannot be modified.No setters: There are no setter methods for the fields, preventing modification of the object's state after it is constructed.
Getter methods:The getter methods allow access to the field values but do not allow modification.
Unmodifiable List:
In this case, we useCollections.unmodifiableList(list)to ensure that the list cannot be modified by external code. The list returned by the getter method cannot be changed because it is unmodifiable.Deep Copying:
If the mutable field is an object (e.g.,Date, custom classes), ensure you create a copy of the object rather than directly storing a reference to it. This prevents external modifications.
Benefits of Immutable Classes
- Thread Safety: Immutable objects are inherently thread-safe because their state cannot change.
- Caching and Hashing: Since the object state is constant, they are safe to use as keys in hash-based collections (like
HashMap). - Predictability: With immutable objects, you can rely on the fact that their state will never change after they are created.

Comments
Post a Comment