Thursday, 4 September 2014

Immutable Objects

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
  1. Immutable objects are inherently thread safe, so you no need to worry about thread safety.
  2. Since immutable objects state can't change, they never get into an inconsistent state.
  3. 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.
  4. 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.
  1. Make all of its fields as final
  2. Declare the class as final
  3. 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.






                                                             Home

No comments:

Post a Comment