In Java, immutability refers an object's state that cannot be changed once it is created. Immutable classes, like String and wrapper classes (Integer, Boolean, etc.), provided benefits such as thread safety and easier debugging. In this chapter, we will learn what immutability is and how to create immutable classes.
An immutable class is a class whose objects cannot be modified after they are created; if you make any change that results in a new object instead of altering the existing one.
For example, the String class in Java is immutable, once a String object is created, its value cannot be changed; if you make any modification, it creates a new String object.
The following are the key rules to create an immutable class:
Use the following syntax to create an immutable class by following the above mentioned rules:
The following example demonstrates how to create an immutable Student class:
Output:
101 Rahul Java
Explanation:
The Student class is declared as final, its fields are private and final, and no setter methods are provided. This ensures that once a Student object is created, its data cannot be modified, making the class immutable.
Although immutable classes provide many benefits, they also have some limitations:
When an immutable class contains mutable objects (such as arrays, lists, or custom objects), it returns direct references that can break immutability. To prevent this, deep copying is used so that the internal state cannot be modified from outside the class.
It has the following syntax:
The following example demonstrates how deep copy helps maintain immutability:
Output:
80
Explanation:
In this above example, even though the original array is modified, the internal state of the Student object remains unchanged because deep copies are used.
We request you to subscribe our newsletter for upcoming updates.