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 the Immutability of a class with a mutable reference?

You May Also Like:

What are common multi-threading issues faced by Java Developers?
What are different states of a Thread? What does those states tell us?
What happens when wait() & notify() methods are called?
What is difference between sleep(), yield() and wait() method?
What is difference between intrinsic synchronization and explicit locking using Lock?
What will happen when an exception arises from within a synchronized code block? Will lock be retained or released?
What is difference between Executor submit() and execute() method?

If you have any feedback or suggestion please feel free to drop in below comment box.

2 thoughts on “How can we maintain Immutability of a class with a mutable reference ?

  1. Mahesh

    Great work Kishan…Really You Have done awesome work thank’s a lot…

    Reply

Leave a Reply

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