final
, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler). Immutable objects carry some very desirable characteristics:
- they are simple to understand and easy to use
- they are inherently thread-safe: they require no synchronization
- they make great building blocks for other objects
final
is going to help us define immutable objects. First in labelling our object as immutable, which makes it simple to use and understand by other programmers. Second in guaranteeing that the object's state never changes, which enable the thread-safe property: thread concurrency issues are relevant when one thread can change data while another thread is reading the same data. Because an immutable object never changes its data, synchronizing access to it is not needed. Create an immutable class by meeting all of the following conditions: - Declare all fields
private final
. - Set all fields in the constructor.
- Don't provide any methods that modify the state of the object; provide only getter methods (no setters).
- Declare the class final, so that no methods may be overridden.
- Ensure exclusive access to any mutable components, e.g. by returning copies.
No comments:
Post a Comment