Immutable Object in Java

What is immutable class

whose state cannot be changed once created.

Steps for creating the immutable Class
1-All fields are final and private
2-No setter method is exposed
3-Don't allow the subclass to override the method 
mark class as final

more sophisticated mark the constructor as private

4-if the instance field includes the reference to the mutable objects, never allow those objects to be changed

for this pass the mutable object in the constructor

Benefits of immutable
1-Thread safe (Synchronization and concurrency)
2-copy constructor and clone are useless

Example to Create immutable

example -1
public class Person {                                                          
   private final String name;                                       
                                                                                              
   public Person(String name, String mobile) {       
       this.name = name;                                              
   }                                                                                
   public String getName(){                                       
       return name;                                                        
   }                                                                                
}

in this class it only contains immutable objects 
example-2
if it contains the mutable objects then eg java.util.date - even you store it in final you can change the value of variable


public class Person {
    public final Date DOb = new Date();
Person(){
System.out.println(DOb);
}
   public Date getDate(){
    DOb.setTime(1212);
     return DOb;
   }
   public static void main(String[] args) {
    Person p = new Person();
    System.out.println(p.getDate());
}

}

in the previous example you have changes the value of the final object, so to overcome this 
 public Date getDate(){
     return (Date) DOb.clone();

   }

when some one fetch your object you are returning the clone of your object your actual object never hurts and your class us successful immutable 


Why String Is Immutable?

1- String resides in pool, The String pool cannot be achieve without String is immutable
2- String is an object and to treat it as an literal it is necessary to create it as immutable


  String A = "Test";
  String B = "Test";
Now String B called "Test".toUpperCase() which change the same object into "TEST", so A will also be "TEST" if it is not immutable which is not desirable.


3-Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
if I mark reference as final you cannot change the object to which it is referring. and also since it is immutable so you even cannot change the content, so it helps in your security features

4- Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.

5-Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).

6-Best supported for the key in the Hashmap, since it also caches the hashCode so best retrieval and insertion.

7-Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded
you can never change the value of the variable which is being used in the class loading


Comments