An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is fixed for the lifetime of the object, so no changes can ever be observed.
- An immutable object can be in exactly one state, the state in which it was created
- Immutable objects are inherently thread-safe; they require no synchronization. Therefore, they can be shared freely
- You don’t need to make defensive copies of them as they would be equivalent to the originals
- Classes should be immutable unless there’s a very good reason to make them mutable
- Declare every field private final unless there’s a good reason to do otherwise
To make a class immutable, follow these five rules:
- Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
- Make all fields final.
- Make all fields private. This prevents clients from obtaining access to mutable objects referred to by fields and modifying these objects directly.
- Ensure that the class can’t be extended. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
- If the instance fields include references to mutable objects, don’t allow those objects to be changed:
- Don’t provide methods that modify the mutable objects.
- Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.