How to Create Immutable Classes in Java
Introduction
Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes may be present in a single Java program. While certain classes can be immutable, others can be mutable. A class that cannot have its contents changed is said to be immutable. In simple words if the state of immutable objects instances doesn't change even after initialization, then those classes are called immutable classes in java. For instance, the value of the immutable class String never changes after it has been created.
How is an Immutable Class Created?
Many classes, including String, Boolean, Byte, Short, Integer, Long, Float, Double, etc. are immutable. In essence, the String class and its respective wrapper classes are considered to be immutable. we can also establish immutable classes by developing final classes with final data members.
To create an immutable class, we need to follow a few steps, and those steps are given below.
Steps
The steps below must be completed to construct an immutable class in Java.
- Declare the class to be final to prevent extensions. The purpose of making the class final is to avoid inheriting from any other classes. It prevents us from extending a class when we use final with a class.
- Additionally, the data members must be made final so that they cannot be modified after being initialized with the aid of a constructor
- Make all fields private to prevent immediate access. They are inaccessible from outside the class, so the modification of their respective values is undone.
- The getter and setter methods are used in object-oriented programming to retrieve and set values, respectively. So don’t try to give variables setter methods.
- By making all mutable data fields final, we ensure to assign values only for one time.
- Utilize a constructor that performs deep copying to initialize each field. For further understanding as for the getter methods, they return the deep copy of the object rather than the original. This is because if the getter functions return the actual object to anything beyond the class, the class will no longer be immutable.
- A deep copy should also be used as the first step in the parameterized constructor. This is since, in the absence of a deep copy, an object's data member or property can be changed outside of the class using a reference to the object.
An example for creating immutable classes in Java
In the given program, we can learn about how an immutable class is designed. As mentioned in the above points, all the data fields should be private, and we cannot use mutator methods like the setter method. And, apart from the mutator method, accessor methods should also not be used.
Code
// Simple Java program on working with immutable class
import java . io . * ;
public class Employee
{
public static void main ( String s [ ])
{
private int age ;
private String name, location ;
// given below is the default constructor with no parameters in employee class
public Employee ()
{
}
// given below is overloaded constructor with two parameters in class employee
public Employee (String name, int age)
{
this . name = name ;
this. age = age ;
// Given below is overloaded constructer with three parameters in employee class
public Employee ( String name, String location , int age )
{
this ( name , age );
this . location = location ;
}
public String getName ( )
{
return name;
}
public String getLocation ( )
{
return location;
}
public int getAge ( )
{
return age ;
}
} // Main
} // Employee class
The Importance of Immutable Classes
Immutable classes have several benefits, particularly when used properly in a multi-threaded context. The sole drawback of these classes is that they use more memory than regular classes since each time they are modified, a new object is produced in memory. However, developers shouldn't overestimate this drawback because the benefits these classes offer much outweigh their memory usage.
And finally, an object is said to be immutable if it can only ever provide one state to other objects, regardless of how or when those other objects invoke its methods. If so, it satisfies any definition of thread safety.