Design Pattern - Immutable Class - How to implement an Immutable Class ?

Immutable objects are instances whose state doesn’t change after initialization. Immutable Class is a class using which only immutable objects can be made. For example, String is an immutable class and once instantiated its value never changes.

Immutable objects are good for caching purpose because you don’t need to worry about the value changes. Other benefit of immutable class is that it is inherently thread-safe, so we don’t need to worry about thread safety in case of multithreaded environment.

We can create an immutable Class using following steps

  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • 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 Program

package immutable;
final class ImmutableClass1 {
    private final int id;
    private final String name;
    public ImmutableClass1(int id, String name) {
            this.id = id;
            this.name = name;
    }
    public int getId() {
            return id;
    }
    public String getName() {
    return name;
}

@Override
public String toString() {
      return "ImmutableClass1 [id=" + id + ", name=" + name + "]";
}

class Mgr8 {
      public static void main(String[] args) {
          ImmutableClass1 obj1 = new ImmutableClass1(10, "Sashi");
          ImmutableClass1 obj2 = new ImmutableClass1(20, "Keerthana");
          System.out.println("obj1 : " + obj1);
          System.out.println("obj2 : " + obj2);
      }
}

Output:

obj1 : ImmutableClass1 [id=10, name=Sashi]
obj2 : ImmutableClass1 [id=20, name=Keerthana]
Here object got initialized in contructor, No setter methods are there to modifyObject's State.
Object's attributes declared with final, so object's attributes cannot be modified again.
Object's attributes declared with private, so that direct access is not allowed. Here anyone can get the particular object's attribute by using getter Methods, but
they cannot set its value.

Why is String immutable in Java ?

1. String Pool

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. To Cache its Hashcode

If string is not immutable, One can change its hashcode and hence not fit to be cached.

3. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.