How to create an immutable class in java

Here we will see how to create an immutable class in java.

  • Step 1:- Define class as final.
  • Step 2:- Make fields as private and final.
  • Step 3:- Make the constructor private and create an instance within factory methods.
  • Step 4:- Initialize the field through the constructor.
  • Step 5:- Don’t define the setter method.
  • Step 6:- provide getter method for the corresponding fields.

 

final class ImmutableExample {
	private final String name;

	private ImmutableExample(String name) {
		this.name = name;
	}

	public static ImmutableExample getInstance() {
		return new ImmutableExample("ram");
	}

	public String getName() {
		return name;
	}

}

public class Test {
	public static void main(String[] args) {
		ImmutableExample m = ImmutableExample.getInstance();
		System.out.println("name  :-" + m.getName());

	}
}

Output is – name :-ram

 

In the interview, you might encounter the questions,  why we are making classes and variables final and also you may be asked about other points, why we are doing? Let’s see all points in details.

Why are we defining a class as final? 

When we declare a class as final, another class will not able to extend it.

Make fields as private and final.

By making fields private, we have restricted, it will be accessible through the only encapsulation.

Make the constructor private and initialize the field through the constructor.

We are defining constructor as private and initializing the field inside it, not through setter so that we can’t change the value later through the setter.

Provide factory method to get the object of your immutable class.

Since we have declared constructor as private we can’t create an object of that class outside of class. So how we will get the object, we have a factory method which will be used to get the object. You can do something like below, in other classes to get your immutable object.

ImmutableExample m = ImmutableExample.getInstance();
		

Don’t define the setter method.

We don’t want to modify the name value.