Immutable class in Java

All the wrapper classes of primitive date types are immutable, immutable is a concept whose state or values cannot be changed once they are declared. If we try to change any value of the immutable class objects then instead of changing its original value it will create a new Object of same type and return with the new value which we trying to change.

To implement Immutable Class in Java we need to follow the below steps.

  • The class should not be extended, this can be done using final keyword
  • The class should not allow setter method, this can be done by not using any assigning methods.
  • Make sure all the fields of Immutable class are final.
  • In case if your using customized class object as a field in Immutable class, perform the deep copy.

Immutable Class example in Java


<-PREV NEXT->