Sunday, 18 May 2014

How to make a class Immutable in Java - Example & Explanation

What is immutable class in Java? And How to make a class immutable in java? Are two very popular and hot topics as if today. In this particular blog we will look into these two in details and will try to understand benefits if immutable classes in context of Java Language.

What is Immutable class in Java ?

In Java an immutable class is a class whose object’s state can not be changes once created, or any modification on immutable object’s results in another immutable object. Even JDK itself contains a number of immutable classes like String, Float and other wrapper classes. To understand immutable class clearly we can take a simple example of String and StringBuffer classes, any modification on String object i.e. substring, concat ..etc results in a new immutable object while operations performed on StringBuffer class does not create a new object instead modifications are refleted on exiting object only.

How to make a class immutable in Java ?

Let us now discuss how to make a class immutable, there are a number of ways to get an immutable class. Even Java Documentation points out certain guidelines on the same, which we will follow here to get an immutable class.

1) Never provide a setter method for the class, setter methods are used to change the state of a class’s members. This is what we want to prevent here.

2) Make all fields private and final, this will make them non accesable outside the class and their values can not be changed because of being final.

3) Make the class final, so that the class can not be subclassed. This will prevent the class’s methods from overriden.

4) Special attention needs to be applied with mutable reference variables, with reference variables even final can not prevent their value to be changed. The simplest way to prevent reference variables’s vales is to not provide actual object and provide a copy of them.

5) Make the default constructor of the class private and provide instances with a factory method.

Benefits of making a class Immutable

1) Thread-safe hence can be used in concurrent environment without synchronization.
2) Immutable objcts can be used to boost memory, we can simply save them and serve again and again.

That’s all about immutable classes and objects in java, we cam across what is immutablity ? What are immutable classes in Java ?, How to create a class immutable in Java ? and benefits of immutable classes in Java. In upcoming blogs we will see more about Java and Other opensource technologies.