How to Create Immutable Class in Java?

An Object is said to be immutable if its state can not change after modification. For instance, String and all the wrapper classes in java are immutable.

If we try to modify an immutable class, it will create a new object. Hence immutable objects are not modifiable.

Rules to create Immutable Class

  • Create a final class.
  • All the data members of the class must declare private.
  • All mutable fields should be final.
  • Instantiate all the fields in the parameterized constructor with a deep copy to avoid modifying fields using reference.
  • Remove setter methods.
  • Provide getter methods for access.
  • Return defensive copy of a collection in the getter method instead of reference.

Immutable Class Example

import java.util.LinkedList;
import java.util.List;

public final class Immutable {
	private final int id;
	private final List<Object> list;
	private String name;

	public Immutable(int id, List<Object> list, String name) {
		super(); = id;
		this.list = list; = name;

	public int getId() {
		return id;
	public String getName() {
		return name;

	public List<Object> getList() {
		return new LinkedList<>(list); // defensive 

import java.util.LinkedList;
import java.util.List;

public class Driver {
	public static void main(String[] args) {
		List<Object> lst = new LinkedList<Object>();
		Immutable im = new Immutable(10, lst, "Jonny");
		//,modify list
		System.out.println(im.getList()); //remain unchanged

[hello, world]
[hello, world]

We can see from the above output, even after modifying the collection the values are not changed.

Please write a comment, if you find anything wrong or suggestion to improve about the topic.


Leave A Reply

Your email address will not be published.