An
immutable object is one whose state can't change after instantiation.
String and Integer classes are some of the examples of immutable
classes in Java.
Benefits
- Immutable objects are inherently thread safe, so you no need to worry about thread safety.
- Since immutable objects state can't change, they never get into an inconsistent state.
- Since the properties(fields) of immutable objects can't change, you can cache the results of the operations performed on immutable objects and reuse the result.
- Immutable objects are best fit to use them as keys in HashMap.
Guidelines
for writing immutable classes
You
can make a class immutable by making below changes to your class.
- Make all of its fields as final
- Declare the class as final
- Any fields that reference to mutable objects such as Array, collections etc., make those as private, don't expose the data to outside the class(by returning the reference from function), and don't change the state of referenced data after construction of object.
No comments:
Post a Comment