An object whose state does not change once it is instantiated is called immutable object.
Immutability is particularly useful in multi-threaded programs, where race conditions can lead to unpredictable program behavior. Because methods of immutable objects do not change their state, such methods avoid race conditions without the need for synchronization. Hence one thread won’t corrupt a value used in another thread.
Examples of immutable objects from the JDK include String and Integer.
Let’s see how an immutable object behave with an example
str_name is ABCD
Here you can notice that value of str_name has not changed because the String is immutable and we cannot change the value once it is initialized. We can append a value to any other string value as below.
myString = myString + ” Guest”;
Here we are creating a new string object while doing append operation. Hence if you want to use any string append operation in a loop body try using StringBuffer instead of using String object.
Creating Immutable object
You can use the following strategy for creating immutable objects
1) Fields must be private and final.
2) make sure that methods can’t be overridden. You can ensure this by defining methods as final
3) Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods
4) Do not provide any methods which can change the state of the object in any way not only just setXXX methods, but also any method which can change state.
Now let’s create an immutable class called ImmutableClass
In the above example you can notice that ;
– Class is defined as final to make sure that this class is not extending in any other class.
– All the fields, empName and age are defined as private and final
– There is no setter methods which will alter the field values
Now we can create the class to access this immutable class.
Here you can notice that , state of this object does not change once it is instantiated.