Most of us know about mutable and immutable concept and advantages of immutable class in java.
But many of those think we can not make our own java class as immutable and it is by pre defined. It is not true, we can make our own classes as immutable.
Any way as we discussing immutability concept I want to discuss the advantages of immutability concept here.
Benefits
Immutable classes
1) Don’t provide “setter” methods
But many of those think we can not make our own java class as immutable and it is by pre defined. It is not true, we can make our own classes as immutable.
Any way as we discussing immutability concept I want to discuss the advantages of immutability concept here.
Benefits
Immutable classes
- Are automatically thread-safe and have no synchronization issues
- Do not need a copy constructor
- Do not need an implementation of clone
- Allow hashcode to use lazy initialization, and to cache its return value
- Do not need to be copied defensively when used as a field
- Make good Map keys and set elements (these objects must not change state while in the collection)
Making Class as Immutable
Java Documentation as itself some notes on this concept you can find that here
1) Don’t provide “setter” methods
Setter methods are meant to change the state of object and this is what we want to prevent here.
2) Make all fields final and private
Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them
3) Declare class as final
Don’t allow subclasses to override methods
4) Attention with mutable instance variables in class
Always remember that you can have either mutable or immutable instance variables, identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.
Example :