Saturday, March 21, 2015

How to create immutable class in java??

How to create Immutable class?

An immutable class is one whose state can not be changed once created. There are certain guidelines to create an class immutable. In this post, we will revisit these guidelines.

Example to create Immutable class

In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method.
  1. public final class Employee{  
  2. final String pancardNumber;  
  3.   
  4. public Employee(String pancardNumber){  
  5. this.pancardNumber=pancardNumber;  
  6. }  
  7.   
  8. public String getPancardNumber(){  
  9. return pancardNumber;  
  10. }  
  11.   
  12. }  

The above class is immutable because:
  • The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
  • The class is final so we cannot create the subclass.
  • There is no setter methods i.e. we have no option to change the value of the instance variable.
These points makes this class as immutable.

No comments:

Post a Comment