How to Create Immutable Class in Java

An immutable class is a class whose object cannot be modified once created. Any effort to modify the object will result in the creation of another immutable object.
For instance, String class is an immutable class. Once an String object is created, an effort to alter that object results in the creation of another String object.

The immutable object can be created by following rules:

  1. Make class final − class should be final so that it cannot be extended.
  2. Make each field final and private − Each field should be final so that they cannot be modified after initialization.
  3. Create getter method for each field. − Create a public getter method for each field.
  4. No setter method for each field. − Don’t create a public setter method for any of the field.
  5. Create a parametrized constructor − Such a constructor will be used to initialize properties once.

An example of an immutable class:

public final class User {
private final String name;
private final String address;

public User(String name, String address) {
    this.name = name;
    this.address = address;
}

public String getName(){
    return name;
}

public String getAddress(){
    return address;
 }
}

This is the example of immutable Java class, as its state can not be modified once initialized.

Advantages of immutable class:

  1. Immutable objects are thread-safe and doesn’t need synchronization in multi-threaded environment.
  2. It is safe to share the immutable objects among multiple threads as its state cannot be modified.
  3. Immutable objects can be reused as it can get cached and reused later when needed.

Pankaj

panky.geektainment

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment