Tuesday, 3 June 2014

What are the immutable classes in Java?&how to create immutable class& what are the conditions?


       Normally in java String,java.lang.Math & Wrapper classes are the immutable classes.
To create class immutable,you need some steps then it will become immutable class

 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.

    See below example,
                  
                       package com.adnjavainterview;
                       public final class Immutable{
                               private final int id;
                               private final String name;
                               public Immutable(int a,String n){
                                       id=a;
                                       name=n;
                               }
                               public int getId() {
                                       return id;
                               }
                               public String getName() {
                                       return name;
                              }
                      }
     
      Benefits Of   Immutable Classes in Java:--   

1)
Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.

2)  Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.
    
3) Immutable object boost performance of Java application by reducing synchronization in code.

4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers. 

Related Post:-

No comments:

Post a Comment