How can we maintain Immutability of a class with a mutable reference ?

By | August 15, 2019

In this blog post we will discuss about one of the very important java interview question How can we maintain Immutability of a class with a mutable reference ?

To create an immutable class, you must follow the below steps?

  1. Make your class final, so that no other classes can extend it.
  2. Make all instance variables private & final, so that they’re initialized only once inside the constructor and never modified afterward.
  3. Provide only getter methods don’t provide setter methods.
  4. If the class holds a mutable object:
    • You make sure to always return a clone or defensive copy of the field and never return the real object instance from getter method.

Let’s try to understand above points using an example

You can see How we made Employee.java class immutable

Address is a Mutable class and it’s reference used by Employee class

MyUtil.java is a Utility class used to convert  String into Date 

Finally We have Client program which makes use of Immutable class

Sample Output of above program:

 That’s all about When How can we maintain Immutability of a class with a mutable reference ?
If you have any feedback or suggestion please feel free to drop in blow comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *