Tuesday, 3 June 2014

What are the immutable classes in Java? How to create immutable class and What are the conditions?

       Normally in java String, java.lang.Math and 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){
                               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