An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object.
JDK immutable classes: String, the boxed primitive classes(wrapper classes), BigInteger and BigDecimal etc.
How to make a class immutable?
1. Don’t provide any methods that modify the object’s state (known as mutators).
2. Ensure that the class can’t be extended.
3. Make all fields final.
4. Make all fields private.
This prevents clients from obtaining access to mutable objects referred to by fields and modifying these objects directly.
5. Make defensive copies.
Ensure exclusive access to any mutable components.
If your class has any fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects. Never initialize such a field to a client-provided object reference or return the object reference from an accessor.
Ensure that the class can’t be extended ?
Now, suppose I do the following:
1. They are less prone to error and are more secure.
2. Immutable classes are easier to design, implement, and use than mutable classes.
3. Immutable objects are thread-safe so there is no synchronization issues.
4. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
5. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).
6. Immutability makes it easier to parallelize program as there are no conflicts among objects.
7. The internal state of program will be consistent even if you have exceptions.
8. References to immutable objects can be cached as they are not going to change.(i.e in Hashing it provide fast operations).