Immutable
objects are simply objects whose state (the object's data) cannot change after
construction. Examples of immutable
objects from the JDK include String and Integer.
Immutable objects
greatly simplify your program since they:
1) Are simple to construct, test, and use.
2) Are
automatically thread-safe and
have no synchronization issues.
3) Do
not need a copy constructor.
4)Allow hashCode to
use lazy initialization, and to cache its return value
5)Do
not need to be copied defensively when used as a field
You can make a class immutable by following these
guidelines:
1) Ensure the class cannot be overridden - make the class final, or use
static factories and keep constructors private
2)Make fields private and final
3)Do not provide any methods which can
change the state of the object in any way - not just setXXX methods, but any method which can
change state
No comments:
Post a Comment