«Back to Home

Core Java

Topics

How to create Immutable class in Java

Create immutable class
 
In Java, immutable means unchangeable. String is an immutable class and if once we instantiate its value , we can’t change it.
 
All the wrapper classes and String class are immutable in Java like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.
 
We can create immutable class by creating class as final. It means with the use of final keyword, we can create immutable class in Java.
 
To create immutable class in Java, we have to perform the steps, given below.
  1. Declare the class as final. Thus, it can’t be extended.

  2. Make all fields as private. Hence, that direct access is not allowed.

  3. Don’t provide setter methods for any variable.

  4. All mutable fields make as final. Thus that, its value can be assigned only once.

  5. Initialize all the variables through a constructor performing deep copy.

  6. Use object cloning in the getter methods to return a copy.
Let’s see an example of Immutable class.
 
In this example, we created a final class Student. It has one final variable, a parameterized constructor and getter method.
 
Code
  1. public final class Student {  
  2.     final String studentID;  
  3.   
  4.     public Student(String studentID) {  
  5.         this.studentID = studentID;  
  6.     }  
  7.   
  8.     public String getstudentID() {  
  9.         return studentID;  
  10.     }  
  11.   
  12. }  
23

In the example, class is immutable because the instance variable of the class is final. Thus, we cannot change the value of it after creating an object. This class declares as final. Thus, we cannot create the subclass and there are no setter methods. Thus, we have no option to change the value of the instance variable.
 
Summary

Thus, we learnt that we can create immutable class by creating class as final and also learnt it’s some other important steps to create immutable class in Java.