An immutable object can be defined as an object that will not change state after it is instantiated. An immutable object can be made by defining a class which follows following rules:
- The class is to be marked as final.
- The member variables are private and final so that they are not exposed.
- Class should not have setter methods.
- The state of the objects should not be changed in any methods of the class.
Example of Immutable class:
public final class Employee
{
final String pancardNumber; //final variable
public Employee(String pancardNumber)
{
this.pancardNumber=pancardNumber; //initialization of final variable through constructor
}
public String getPancardNumber() //getter method
{
return pancardNumber;
}
}
Benefits of programming with immutable objects:
- Immutable objects are thread-safe so no synchronization issues i.e in mutable objects, multiple threads are trying to change the state of the same object, leading to some threads seeing a variable state of the same object, depending on the timing of the reads and writes to the concerned object. By having an immutable object, one can ensure that all threads that are accessing the object will be seeing the same state, as the state of an immutable object will not change.
- The internal state of the program will be consistent even if there are exceptions as it is immutable.
- References to immutable objects can be cached for future use as they are not going to change.
.
0 Comment(s)