Immutable Objects in java


If we can not modify the object after creation that object is called Immutable object.
String is the best example for Immutable Object.
Rules for making the objects Immutable:

  1. Class should be final.
  2. Class members should be final.
  3. If we have any mutable object in our class then return the copy of that object through the getter of that class member.

We can create our own immutable objects like as follows:

import java.util.Date;
public final class Employee implements Cloneable
{
   private final String name;
   private final String id;
   Date date;	
   public Employee(String name, String id, Date date)
   {
	this.name = name;
	this.id = id;
	this.date = date;
   }	
   public String getName() 
   {
	return name;
   }
   public String getId() 
   {
	return id;
   }
   public Date getDate() 
   {
	return (Date)date.clone();
   }
}


In the above example we have one class Employee which have three members , two are String which are already immutable and one is Date which is mmutable , so we need to take care one thing that we should return copy of the mutable member instead of the original object.
We can say that one use of cloning is to make an object Immutable.

Note: Main benefit of immutable object is that multiple threads can access the immutable object outside the synchronization block , it improves the performance.