Monday, 11 August 2014

How to create Immutable Object and class in java

How to create Immutable Object and class in Java this is most commonly question asked by interviewer.
Before going to explain how to create Immutable, let's understand what is means of Immutable.
Immutable means not changeable, once created.e.g There is a multiple scenario when we need object or class that look like final variable. final variable is variable that can not be reassigned again.
The main use case of Immutable is-
  1. Object can be shared in threaded environment, because no thread can modify the object. Hence in this case synchronization block is also not required and if program does not has synchronization block then performance will be more.
  2.  Suppose you are using object as a key in HashMap or Hashtable then making immutable key means always value can be accessible by key. assume if key is not immutable then after set value in hashmap or hashtable if any body change the key from outside then accessing the value by key is tough.
  3. Caching is other use case. if you cache immutable object then any time can be accessible without any modification.
 Here in this topic immutable means can not modified/changed/updated/reassigned, once created.

Now the question is how to create immutable object and class?
It's very easy just follow some basic points during the creating class, which are-
  1. Don't provide setter methods this will prevent the fields value to be modify from outside or inside of the class.
  2. All the fields of class should be final. This will prevent the fields to be reassigned again.
  3. All the fields of class should be private.This will prevent the fields to be access from outside or from reflection api.
  4. Create the final class. This will prevent the class from subclassing. e.g class can not be overridden.
  5. Make sure no such methods is present in the class that is updating the state/fields.
  6. Declare the constructor of the class as private and add a factory method to create an instance of the class when required.
For example-
    each person has unique mobile number so below immutable class is created to store mobile number for person class-

                   final class ImmutablePersonClass{
                          private static ImmutablePersonClass instance = new ImmutablePersonClass();
                          private long final mobileNumber;
                        
                          private ImmutablePersonClass(long mobileNumber){
                             this.mobileNumber= mobileNumber;
                         }
                       
                          public long getMobileNumber(){
                            return mobileNumber;
                          }
                         
                          public ImmutablePersonClass getImmutablePersonClass(){
                           return instance;    
                          }

                     }

No comments:

Post a Comment