Monday, April 10, 2017

How to write immutable class?

We can create a immutable classes in different ways. The below strategy is used as a common strategy to create it.

1. Set all the properties of on object in the constructor.
2. Mark all of the instance variables private and final.
3. Don't define any setter methods.
4. Don't allow referenced mutable objects to be modified or accessed directly.
5. Prevent methods from being overridden.

The first rule defines how we create the immutable object, by passing the information
to the constructor, so that all of the data is set upon creation.

The second and third rules are straightforward, as they stem from proper encapsulation. If the instance variables are private and final , and there are no setter methods, then there is no direct way to change the property of an object. All references and primitive values contained in the object are set at creation and cannot be modified.

No comments: