Tuesday, 28 November 2023

Creating Immutable Custom Class in Java

 A frequent Java interview question is : 

How to create a Class which is immutable? 

Like any other question, the answer begins with the understandig what do we really mean by the underlying concept - in this case : immutablity !!! 

Making a class immutable entails ensuring two solemn contracts : 

  1. Class is closed for extension i.e it cannot be inherited. (why is that necessary? ans at bottom)
  2. Once the object is created, the state of fields cannot chage till its existence in JVM.
In other words, A variable/class of an immutable type may only be changed by re-assigning to that variable. When we wish to only modify some portion of an immutable, we are compelled to reassign the whole object.

Let's take Student class as an example. 




This class can be made Immutable in following way (observe the Student class carefully) : 



KEY TAKEAWAYS : 
  1. finalize class 
  2. set class mebers as "private" and "final
  3. Assign new object to instance variable by copying all values 
  4. remove all setters() 
  5. return duplicate(new object) in getters() instead of actual instance variable

Finally answer to the question : Why do we need to declare an Immutable class final? 

Well the question is quite debatable. 

There are several reasons why we need to declare a class as final to make it immutable.
  1. To prevent subclasses from overriding methods and changing the state of the object.
    • If a class is not final, a subclass could override a method and change the state of the object. This would violate the principle of immutability, which states that the state of an object cannot be changed once it is created.
  2. To ensure that the object is thread-safe.
    • Immutable objects are thread-safe because they cannot be changed by multiple threads at the same time. This is important for objects that are shared between multiple threads, such as objects in a cache.
  3. To improve performance.
    • The JVM can make some optimizations for immutable objects, such as caching the hash code of the object. This can improve the performance of applications that use immutable objects.
  4. To make the code more readable and easier to understand.
    • Immutable objects are easier to reason about because their state cannot change. This makes the code more readable and easier to understand.

~ Happy Coding ~