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.
- Declare the class as final. Thus, it can’t be extended.
- Make all fields as private. Hence, that direct access is not allowed.
- Don’t provide setter methods for any variable.
- All mutable fields make as final. Thus that, its value can be assigned only once.
- Initialize all the variables through a constructor performing deep copy.
- 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
- public final class Student {
- final String studentID;
- public Student(String studentID) {
- this.studentID = studentID;
- }
- public String getstudentID() {
- return studentID;
- }
- }
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.