Immutable Class

Cannot be changed (mutated)

Whenever changed - a new instance is created

What makes a class immutable?

  • Instance variable is final (value can't be changed)
  • class = final - So subclass can't be created
  • No setters

How to create an immutable class

OOP#Final

  • Create final class with all final data members.

Getters via OOP#Deep Cloning

  • Whichever way you decide to initialize the object and add value to these fields make sure to perform a OOP#Deep Cloning for any reference fields.

  • You have to be careful when there's a reference in the members as well. For example, arrays in Java are mutable objects.

  • Although, final prevents reassignment of the reference itself to a different memory location, it does not prevent the object's members from being modified. This ensures deep immutability.

  • If the reference member itself is immutable (for example, String in Java), then you can do without deep cloning while returning it through the getter.

💡 Use Object cloning#`clone()` to perform deep cloning. You can use the same method for any Object cloning#`Cloneable` object.

Setting values

  • All values are set in the constructor and remain unchanged after that.
  • Setters: While it is possible to have one-time setters, which only set the values once, it is not a common approach. It doesn't typically align with expectation of immutability, where any object is unchangeable after creation. It can also lead to issues in case of multithreading unless synchronized.

final public class ImmutableClass {
	final private int id;
	final private Map<String, Integer> m;
	final private int[] arr;

	public ImmutableClass(int id, HashMap<String, Integer> m, int[] a){
		this.id = id;
		this.m = new HashMap<>();
		this.arr = arr.clone();

		for (String key : m.keySet()) {
			this.m.put(key, m.get(key));
		}
	}

	public int getId() {
		return id;
	}

	public int getMapValue(String key){
		return this.m.getOrDefault(key, -1);
	}

	public int[] getArr(){
		return arr.clone()
	}

}

Benefits

The main benefits of immutability come in case of multi-threaded applications, functional programming and high-security systems.

  • Thead safety
  • Predictable behavior
  • Enhanced security: ensures that sensitive data cannot be modified after its created preventing unintended or malicious change.
  • Caching:
    • Immutable objects can be safely shared across different parts of program.
    • Hashcodes for hash-based structures can be precomputed and cached - since they won't change
  • Works well with Functional Programming
  • Immutability is one of the principles of functional programming
  • Immutable objects ensure that functions don't modify anything outside their scope

In addition, immutability is also important if the object of the class is being used as a key in a Hashtable.

Use cases

  • Value objects. For example, Integer in Java
  • Custom objects as Hashtable keys

References

© 2025 All rights reservedBuilt with Flowershow Cloud

Built with LogoFlowershow Cloud