How to create immutable class in java – Simplest Example

We create immutable class in java by making the class fields final and private, and by providing getter setter method, and returning new object with new data on object modification

Technical interview question is that, make a user defined class immutable. Write a simple immutable class and Explain it. also, demonstrate that it is immutable in main program.

Note that an Immutable object, means once object is created, we cannot change its state. In other word, we cannot modify its content. if you try to modify, it will create a new object with new data.

Answer:

To create immutable class in java (User defined class), we can provide a method for modifying object data but the modification is stored in different object. That means, we can keep field as final and private and provide a public setter method, but that setter method will return a new object of the class with modified data without touching the original data.

Here are the simple steps to make user defined class immutable

1)Make class field final and private. final, so that class itself will not be able to change it accidently once initialized. Private, so that it cannot be accessible outside of the class

2) Provide public getter method to access the data outside of the class.

3) Provide public setter method and in setter method, create new object of the class with new data and return it.

Example of how to create immutable class in java

/*--------------------------------------------------
 *  User defined immutable class - how to create immutable class in java
 */
class ImmutableClass {
	final private int data;
	
	public ImmutableClass(int data) {
		this.data = data;
	}

	public int getData() {
		return data;
	}
	
	//Provide setter method to set data but
	//but return new object without touching the old object
	public ImmutableClass setData(int data) {

		return new ImmutableClass(data);
	}

}

/*-----------------------------------------------
 * Testing code
 */

public class TestImmutableClass {

	
	public static void main(String[] args) {		
				
		ImmutableClass i1 = new ImmutableClass(1000);
		
		//if we change the value of object i1
		//address will be changed 
		ImmutableClass i2 = i1.setData(5000);
		//i4 get different memory
		System.out.println(i1.getData());
		System.out.println(i2.getData());		
				
	}

}

Output:

1000
5000

NOTE

We are talking about the immutable object, means once object is created, we cannot modify it. However, if we want the class not to be inherited like String class, then we can declare the class as final.

You can view an example of how to stop a class to be inherited in java program. Also, you can read a good note on final keyword in java.

Related Posts