Friday, 19 October 2012

Immutability example using final class


About  Immutable classes objects

If Immutable objects are used properly then it can simplify programming as they are simple to construct, test and use. Immutable objects are automatically thread-safe and have no synchronization issues.
Immutable classes are ideal for representing values of abstract data types, such as numbers, enumerated types etc.Integer, Long, and Float, are immutable in the Java class library.
Immutable objects are used to make good Map keys and Set elements.
Immutable classes can be write in easy way. A class will be immutable if all of the following are true:

  •   The class should be declared as final
  •   All of its(class) fields should be final
  •   this reference should not allow to escape during construction
  •  Any fields that contain references to mutable objects, such as arrays, collections, or mutable 
     classes like Date should be private.
  •  Do not change the state of the referenced objects after construction.
  •  Avoid any methods which can change the state of the object

//This is the sample program for the creation of immutable class.

package com.corejava.gaurav.examples;

public final class ImmutableClassTestExample {
   
    private final int[] myArray;

    public ImmutableClassTestExample(int[] anArray){

        //this.myArray = anArray;//Wrong way not to use like this...
       
        this.myArray = anArray.clone();//Defensive Copy This is the example for pure immutable class
    }
    public String toString(){
        StringBuffer strBuf = new StringBuffer("Number are: ");
        for(int i=0;i<myArray.length;i++){
            strBuf.append(myArray[i]+" ");
        }
        return strBuf.toString();
    }
}


//This is the sample program for the testing of immutability of another class

package com.corejava.gaurav.examples;

public class ImmutableClassCaller {
    public static void main(String args[]){
    int[] array = {15,21};
    ImmutableClassTestExample immutableRef = new ImmutableClassTestExample(array);
    System.out.println("Before Constructing - "+immutableRef);
    array[1] = 55;//change the element
    System.out.println("After Constructing - "+immutableRef);
    }
}

Note:- First remove the comment for the below line
//this.myArray = anArray; and comment this line this.myArray = anArray.clone();
and test for immutability. Again do the reverse and test for immutability, you will get the difference.

In multi-threaded programs Immutability is very important , because then we know that one thread won't corrupt / override a value used in another thread and it's also very useful in a single-threaded programs.


No comments:

Post a Comment