How to create Immutable class in Java

What are immutable classes

Let us understand, How to create Immutable class in Java. Immutable objects are those objects whose states can not be changed once initialized.
Sometimes it is necessary to make immutable class as per requirement. For example, All primitive wrapper classes
(Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java. String class is immutable.
It is also good for caching purpose because once caching is completed it is not required to change.

Benefits of Immutable Class

It is thread safe so there is no need to worry in multi threaded environment for data inconsistency.

To create an immutable class in java, you have to do following steps.

  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Do not provide setter methods (methods that modify fields) for variables. So that it can not be set.
  • Make all mutable fields final so that it’s value can be assigned only once.
  • Initialize all the fields through a constructor doing the deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
  • If the instance fields include references to mutable objects, don’t allow those objects to be changed:
  • Don’t provide methods that modify the mutable objects.
  • Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.
    Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

Simple Example to create Immutable class in java

Here we have created a Employee class which has final instance variable , constructor through which this final instance variable is set.

There is a getter method for retrieving the value of instance variable.

public final class Employee
{
   final String pan;

   public Employee(String pan)
    {
     this.pan=pan;
    }

   public String getPan()
    {
      return pan;
    }

}

Immutable Class Example with Mutable class as a  instance variable

In this example class ha mutable class i.e List which can be added after creating the instance of College class as well.

To deal with this problem we have to code in the below way.

package immutable;

import java.util.ArrayList;
import java.util.List;

public final class College 
{
//mutable class instance variable
List collegeStudents;

College(List collegeStudents)
{
//make clone object and then assign value to instance variable
List cloneObj=new ArrayList();
cloneObj.addAll(collegeStudents);
this.collegeStudents=cloneObj;
}
public List getCollegeStudents() {
List cloneObj=new ArrayList();
cloneObj.addAll(this.collegeStudents);

return cloneObj;
}

public static void main(String[] args)
{
List al=new ArrayList();

al.add(1);
al.add(2);
al.add(3);
al.add(4);

College cObj=new College(al);
System.out.println(cObj.getCollegeStudents());
al.add(5);
System.out.println(cObj.getCollegeStudents());

}
}

Output:
[1, 2, 3, 4]
[1, 2, 3, 4]

Conclusion

We have learned what are immutable class, how to create the immutable class in java, what are the benefits of creating the immutable class in java.

Readers, If you have any query, Please feel free to add in the below Comment box or contact me personally @ techblogstation@gmail.com.

References:

https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

15 Comments

  1. It works quite well for me

  2. Thanks to the wonderful guide

  3. Thanks, it is quite informative

  4. Thanks to the wonderful guide

  5. Thanks for the excellent manual

  6. It works quite well for me

  7. This is truly helpful, thanks.

  8. Very nice article. I certainly appreciate this website. Continue the good work!

Leave a Reply