Wednesday, December 22, 2010

Can we Create Immuteble Classes in java..

Most of the times the Immutable objects are very handy.
The advantages of the Immutable Objects are as follows
  • The content of the Immutable Objects are Immutable which are most widely used in Caching o fan Objects bcoz all the objects will have the same content
  • The Immutable objects are inherently Thread Safe so the Programmer need not to worry about multi- threading concept.
  • Ultimately the content of the Immutable Objects never Changes.even though the programmer created the 'n'  number of objects  all the objects will have the same content, whose value cannot be changed.

The Example of the Above said criteria can be explained in the following Java Example.

To achieve the Immutable Objects follow the below instructions.

  1. Declare the class as final so it can’t be extended.
  2. Make all fields private so that direct access is not allowed.
  3. Don’t provide setter methods for variables
  4. Make all mutable fields final so that it’s value can be assigned only once.
  5. Initialize all the fields via a constructor performing deep copy.
  6. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

 //Immute.java

public final class Immute {

    private final int id;

    private final String name;

     /**
     * Accessor function for mutable objects
     */
    /**
     * Constructor performing Deep Copy
     * @param i
     * @param n
    */

    public Immute(int i, String n){
        System.out.println("Performing Deep Copy for Object initialization");
        this.id=i;
        this.name=n;
      
    }

    /**
     * Constructor performing Swallow Copy
     * @param i
     * @param n
     * @param hm
     */
    /**
    public Immute(int i, String n, HashMap<String,String> hm){
        System.out.println("Performing Swallow Copy for Object initialization");
        this.id=i;
        this.name=n;
        this.testMap=hm;
    }
    */

    /**
     * To test the consequences of Swallow Copy and how to avoid it with Deep Copy for creating immutable classes
     * @param args
     */
    public static void main(String[] args) {
       
        String s = "original";

        int i=10;

       Immute ce = new Immute(i,s);

        //Lets see whether its copy by field or reference
    
        //print the ce values
        System.out.println("ce id:"+ce.id);
        System.out.println("ce name:"+ce.name);
   
        //change the local variable values
        i=20;
        s="modified";
     
        //print the values again
        System.out.println("ce id after local variable change:"+ce.id);
        System.out.println("ce name after local variable change:"+ce.name);
}

}
Output is.....

ce id:10
ce name:original
ce id after local variable change:10
ce name after local variable change:original

No comments:

Post a Comment