Home > Java Interview Questions > How To Create Immutable class and objects in Java

How To Create Immutable class and objects in Java

Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified.

Creating immutable classes in Java is becoming popular, because of concurrency and multithreading advantage provided by immutable objects. Immutable objects offers several benefits over conventional mutable object:
Especially while creating concurrent Java application.
Immutable object not only guarantees safe publication of object’s state, but also can be shared among other threads without any external synchronization.
JDK itself contains several immutable classes like String, Integer and other wrapper classes.
here are few rules, which helps to make a class immutable in Java :
1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Object must be properly constructed i.e. object reference must not leak during construction process.
4. Object should be final in order to restrict sub-class for altering immutability of parent class.

/**
* Simplest way of creating Immutable class
*/
package com.practise.immutables;</code>

/**
* @author skakkar
*
*/

//Class should be final to avoid immutability on risk due to Inheritance and Polymorphism
public final class ImmutableClass {

//Create all fields Final
private final String name;
private final String mobile;

public ImmutableClass(String name, String mobile) {
this.name = name;
this.mobile = mobile;
}

public String getName() {
return name;
}

public String getMobile() {
return mobile;
}

}

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

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment