Q: what is
immutable class?
An
immutable object is an object whose state cannot be modified after it is
created.This is in contrast to a mutable object, which can be modified after it
is created.
Exp :an object that uses
memoization to cache the results of expensive computations could still be
considered an immutable object.
Q:
how to make class immutable ?
1.
Make class as final (Don’t allow Sub classes to override methods)
2.
Make all fields final and private
3.
Don’t provide “setter” methods, but can provide getter.
4.
Do not change the state of the objects in any methods of the class.
Q: Benefits of making a class
immutable:
1. They
are automatically thread-safe and have no synchronization issues.
2.
Immutable objects are good Map keys and Set elements, since these typically do
not
change once created.
3.
Immutable objects are simple to construct, test, and use.
4.
The internal state of your program will be consistent even if you have
exceptions.
5. References
to immutable objects can be cached as they are not going to change.