Immutable objects whose state (i.e. the object’s data) does not change once it
is instantiated (i.e. it becomes a read-only object after instantiation).
Immutable classes are ideal for representing numbers (e.g. java.lang.Integer, java.lang.Float, java.lang.BigDecimal etc are immutable objects), enumerated types, colors (e.g. java.awt.Color is an immutable object), short lived objects like events, messages etc.
The immutable class are written in following guidelines:
Immutable classes are ideal for representing numbers (e.g. java.lang.Integer, java.lang.Float, java.lang.BigDecimal etc are immutable objects), enumerated types, colors (e.g. java.awt.Color is an immutable object), short lived objects like events, messages etc.
The immutable class are written in following guidelines:
- A class is declared as final. (The final class cannot be extended)
- All its fields are final (final fields cannot be mutated once assigned).
- Do not provide any methods that can change the state of the immutable object in any way – not just setXXX methods, but any methods which can change the state.
- The “this” reference is not allowed to escape during
construction from the immutable class and the immutable class should
have exclusive access to fields that contain references to mutable
objects like arrays, collections and mutable classes like Date etc by:
- Declaring the mutable references as private.
- Not returning or exposing the mutable references to the caller
- Immutable classes can greatly simplify programming by freely allowing you to cache and share the references to the immutable objects without having to
- Immutable classes are inherently thread-safe and you do not have to
- Eliminates the possibility of data becoming inaccessible when used as keys in HashMaps or as elements in Sets
No comments:
Post a Comment