Tuesday, 3 June 2014

How to create immutable class in Java?


       Normally in java String, java.lang.Math and Wrapper classes are the immutable classes.

To create class immutable, you need to follow some steps as below,

  •  Declare the class as final so it can’t be extended.
  •  Make all fields private so that direct access is not allowed. Using getter method you can access private fields.
  •  Don’t provide setter methods for variables.
  •  Make all mutable fields final so that it’s value can be assigned only once.
  •  Initialize all the fields via a constructor performing deep copy.
  •  Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

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 re-usability,  you can cache Immutable object and reuse them, much like String literals and Integers. 



 
Related Post:-

No comments:

Post a Comment