Tuesday 3 June 2014

How to create immutable class in Java?

    In  java String, java.lang.Math and Wrapper classes are the immutable classes. In this post, we need to learn how to create immutable class or object in java

To create class as immutable, need to follow the below steps,

  •  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.


       package com.adnjavainterview;

       public final class Immutable{

              private final int id;
              private final String name;

              public Immutable(int a,String n){

              public int getId() {
                     return id;

              public String getName() {
                    return name;


      Benefits Of   Immutable Classes in Java:--   

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