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.

Modifying immutable class results in 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();
		this.id = id;
		this.list = list;
		this.name = 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>();
		lst.add("hello");
		lst.add("world");
		Immutable im = new Immutable(10, lst, "Jonny");
		System.out.println(im.getId());
		System.out.println(im.getName());
		System.out.println(im.getList());
		
		//,modify list
		im.getList().add("moon");
		System.out.println(im.getList()); //remain unchanged
	}

}
10
Jonny
[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.

Recommended:

Leave A Reply

Your email address will not be published.