Monday, February 18, 2013

Immutable Class



Immutable class : A class whose contents can not be changed once created.
Immutable object :  An object whose state can not be changed once constructed.

To create an immutable class following steps should be followed:
  1. Create class as a final.
  2. Make all the members of the class as private and final.
  3. Set the values of members using constructor or in static block only.
  4. Don’t provide any methods that can change the state of the object in any way (i.e not only setter methods, but also any method which can change the state).
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.

E.g.
public final class Person {
      private final String name;
      private final int age;
     
      public Person (String name,  int age) {
            this.name = name;
            this.age = age;
      }
      public int getAge() {
            return age;
      }
      public String getName() {
            return name;
      }
     
}

Immutable classes in java are :  
All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double,  BigInteger

Note  : Immutable objects are automatically thread-safe. Because the state of the immutable objects can not be changed once they are created.


No comments:

Post a Comment