Create Immutable Java Class

If you want to create an Immutable Java Class, you first need to understand the term immutable. The simple definition of immutable is something that is unable to be changed.

The Java String is a great example of an Immutable Class, meaning the value of the String can’t be changed after creation. An object that is immutable cannot be changed after it is initialized. The final keyword also prevents a class from being sub-classed.

Creating your own immutable class in Java is simple, just follow these three steps:

  • Declare the class final
  • Declare all variables private and final
  • Do not provide setter methods for the defined variables

The below very simple class is a good example on how to define a Java class as immutable.

//JavaCodeDepot Sample

package com.jcd.java.interview;

import java.util.HashMap;

public final class ImmutableClass {
	
	
	/////////////////////////////////////
	//Declare all variables as final
	/////////////////////////////////////
	private final int jcdInt;
	
	private final String jcdName;
	
	private final boolean jcdAction;
	
	private final HashMap<String, Integer> jcdHashMap;
	
	
	///////////////////////////////////////
	//Do not create any setter methods
	///////////////////////////////////////
	
	
	//Only allow read access to variables with the getters
	public int getJcdId() {
		return jcdInt;
	}
	
	public String getJcdName() {
		return jcdName;
	}
	
	public boolean getAction() {
		return jcdAction;
	}

}


What are the benefits from creating immutable objects in Java?

  • Immutable Objects are safe in multi-threaded programs
  • Immutable Objects are ideal for Maps and Sets

The popular criticism of immutable objects in the Java programming community is that it can lead to an explosion of objects because your forcing new objects each time something changes, resulting in performance concerns. Because Objects are inexpensive in terms of memory and the advancement of the garbage collector, this is not a concern for most environments.

If you can make your Java Classes Immutable, it’s a good programming practice to do so unless there is some very good reason why a class must be mutable.

Add a Comment

Your email address will not be published. Required fields are marked *