How to Create Immutable Classes in Java: A Step-by-Step Guide

This article will teach you how to create immutable classes in Java. Immutable classes are classes that cannot be changed after they are created. They are useful for classes that represent data because they prevent accidental changes to the data.

To create an immutable class in Java, you need to follow these steps:

  1. Declare the class as final.
  2. Declare all of the class’s fields as final.
  3. Do not allow any methods to modify the class’s fields.
  4. Implement a constructor that sets the class’s fields to their initial values.
  5. Optionally, implement a toString() method to return a string representation of the class’s data.

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.

Conclusion

In this guide, we have shown you how to create immutable classes in Java. We have explained the benefits of immutable classes and shown you how to create them using the Java language.

I hope you have found this guide useful.

Recommended:

Leave A Reply

Your email address will not be published.