Immutable Object-Create your own immutable java class

For programming logic perspective, we need both mutable and immutable object depending upon the requirement. Everything has its own advantages and requirements which depends on the logic we want to implement. JDK is also contained many immutable classes like java String class, so the importance of it can not be ignored. Here I will discuss the correct way of creating our own immutable class.

Let’s start programming in Java: How to set up a computer for java programming?

What is immutability?

It’s a property of an object by which we cannot perform any change in an object once after it’s creation. After creating an object, its state cannot be changed.

The properties of an immutable object can never be changed directly or by any method present in that class.

In many custom defined immutable classes we cannot at all change the content of an object, but in few immutable classes including the String class of Java, If we change the content of the object then it will return another new object with those changes. But the values of the primary object won’t get changed. This behavior of an object is called Immutability.

Even when we have the reference to an immutable object, we can’t change it’s value if the object is immutable. But in case mutable object, if we have the reference to an object then we can change the value of that object.

Let’s demonstrate this by an example. Here we will use “java.lang.StringBuffer” class as a mutable class and “java.lang.String” class as an immutable class.

Here in this example, we have created two objects. One is of String Class and another is of StringBuffer class. In both the object, we have assigned a string value “Hello” through the constructor and after the object created, we tried to add another string literal ” there” with the previous value. Now let’s look at the OutPut of this program.

Here the StringBuffer class object could be changed as StringBuffer is a mutable class, but the object of String class could not get changed because of its immutable nature.

Also check out:

Predefined immutable classes in Java

In Java, there are no of classes present in JDK which are immutable. All the Wrapper Classes and String class is Immutable in nature. There are 8 Wrapper classes present in java.lang package of Java. Those are Byte, Short, Integer, Long, Float, Double, Character and Boolean Class. These all classes are immutable in nature.

How to Create our own immutable class?

Let’s go step by step from the very basic. We are about to create an immutable class and the main objective of an immutable class is, the value or content of its object cannot be changed once it will be created. So we have to stop all those ways by which the content os an object can be changed later.

We can change the value of an object by the processes listed below

  1. By mutator or setter method of the same class.
  2. By changing the value of a field through the reference to the object from a child class.
  3. By modifying the methods by overriding concept from a child class.
  4. If our immutable object is referencing another mutable object of another class, then by changing the value of that mutable object we can change the content of this object. We’ll discuss it below with an example.

So to make an object immutable we have to prevent these possibilities. If these ways of changing the value of an object will be blocked, then that object will nothing but an immutable object.

How can we prevent these possibilities..??!! See the rules given below.

Rules to create immutable class

  1. We should not declare any mutator or setter method inside the class.
  2. Declare all the fields private, so that the fields cannot be accessed from any class extends this class.
  3. Declare the class as final so that any method of this class cannot be overridden.
  4. Take care of all the objects which are referenced by our immutable object. The state of those objects should be immutable too.
  5. Write a parameterized constructor to initialize all the fields.

Example of an immutable class

This Employee class is immutable. The values of Employee object can be set only when it is instantiated. And the state of the object of this class cannot be changed once it is created. We can only read the value by getter methods.

If our immutable class object refers another object

Here in the above example, our custom made immutable class has two fields, name and age. Here the name field is String type and age field is int type. But if any other mutable object will be referenced by our immutable class then the value of our immutable class object can be changed by changing the value of that mutable class object. See the example below for better understanding.

In this example, one of the fields of our employee class object is joiningDate, which is an object of java.util.Date class and Date class is a mutable class. i.e Date class has both getter and setter methods. So we can change the value of the Date object anytime by its reference. So if we write and run the code below

If you run this code the output will be(Depends on current Date and Time)

As we can see the value of joiningDate of the Employee object has been changed. So by changing the value of Date object, it is possible to change the value of Employee object, Which makes Employee object mutable.

To create a perfectly immutable object we should have to fix this also.

To defend this issue, we must go independent of Date object reference. By the reference of the Date class object, the value of joingDate field can be changed anytime. So to get a perfectly mutable Employee object, we should return a constant value always irrespective of the value of Date object. To do so we have to return a new Date object from the getter method i.e getJoiningDate(), rather than returning the value of reference variable of the Date object.

The getter method inside Employee class should be like

Now our class is completely mutable. Value of Employee object cannot be changed in any way.

Do you know How does Fluorescent light work?What is the need for ballast and Starter?!!

Check out How does mobile network work? How it connects two mobile phone?

Advantages and Disadvantages of immutable class

Every perspective has its own advantages and disadvantages. Making an object immutable also cause the same. It is sometimes very useful for the programmers and sometimes problematic. We will discuss both sides of it.

Advantages of immutable object

  • Thread safety is the greatest advantage of making an object immutable. If multiple threads will act on the same object then all the thread will find the same state of the object. Sometimes when both read and write operations takes place on the same object by different threads, some thread fails to read the original state of the object as the value got changed by another thread in case of a Mutable object.
  • It maintains the correctness of the state of the object throughout the execution of the program as it’s value can never be changed.
  • We don’t have to implement external synchronization on an immutable object as it is already Thread-safe.

Disadvantages of immutable object

  • We have to create a different new object every time we need an object with changed value. Because we can not change the value of the existing object.
  • Generally immutable classes have parameterized constructor, which may create difficulties in deserializing immutable objects.
  • The immutable objects cannot be reused which leads to creating a lot of garbage and that way put much load on Garbage Collector.

Add Comment