How to create immutable class in java – Simplest Example

(Last Updated On: April 16, 2018)

Create immutable class in java by making class field final and private, 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.


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







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.