Create Immutable class in Java

In this tutorial, we are going to learn how to create immutable classes in Java. Java provides us with a lot of advantageous features to make our tasks easier and more convenient to use. One of them which we are going to discuss here is how to create an immutable class. By creating an immutable class, we can protect our data from outside intervention.

Whenever an object of the immutable class is created, its value cannot be changed once it is created and initialized i.e. immutable class is a class whose object cannot be changed once it is created and remains the same throughout the life of the object. All the wrapper classes such as Boolean, Integer, Byte, Short, and the String class are immutable. Not only this, we can create an immutable class on our own by declaring classes as final and the data members both final and private.

Creating an immutable class

Some of the important things we need to keep in mind are:

We will never override the methods of the class by the subclasses. And also we will declare the class final so that the subclasses cannot be created. We declare all the data members in the class as private so that no one can access them directly. We declare all the data members in the class as final as well so that the value of the data members cannot get changed after creating the object. A constructor is, then, created for the initialization of all the fields by creating an exact copy of the data(deep copy). We will not add a setter method or any other methods that can change the state or the values of the object. We will only use the getter method here.

Here, in the example below, we will create a final class Immutable. It consists of only one data member declared private as well as final i.e name, a parametrized constructor, and getter function.

The complete code:

import java.util.Scanner;
public class Main
{
     public static void main(String args[])
     {
         Scanner in = new Scanner(System.in);
          String tmp = "Hello ";
          String str;
          System.out.println("Enter your name");
          str = in.nextLine();
          Immutable im = new Immutable(str);
          System.out.println(tmp.concat(im.getMsg()));
          
     }
     final  static class Immutable{
          
          private final String name;
          public Immutable(String name)
          {
               this.name = name;
          }
          public String getName(){
               return name;     
          }
     }
}

After executing the code,

the output:

Enter your name

Meenakshi

Hello Meenakshi

After entering the name, we cannot change or modify the name.

Hope this tutorial was useful.

Leave a Reply

Your email address will not be published.