How To Create Immutable Class In Java - Java Tutorial

How To Create Immutable Class In Java

BLUF: Mastering How To Create Immutable Class In Java is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: How To Create Immutable Class In Java

Java's versatility is unmatched. Learn how How To Create Immutable Class In Java fits into the Java ecosystem and improves your code structure in the tutorial below.

Numerous classes are immutable, including String, Boolean, Byte, Short, Integer, Long, Float, and Double, among others. Essentially, all wrapper classes and the String class are immutable. It is also possible to establish an immutable class by defining a final class with final data members, as illustrated below:

Example to create Immutable class

In this instance, we have established a final class called Employee. It includes a single final data field, a constructor with parameters, and a method for retrieving the data.

ImmutableDemo.java

Example

public final class Employee

{  

final String pancardNumber;  

public Employee(String pancardNumber)

{  

this.pancardNumber=pancardNumber;  

}

public String getPancardNumber(){  

return pancardNumber;  

}  

}  

public class ImmutableDemo

{

public static void main(String ar[])

{

Employee e = new Employee("ABC123");

String s1 = e.getPancardNumber();

System.out.println("Pancard Number: " + s1);

}

}

Output:

Output

Pancard Number: ABC123

The above class is immutable because:

  • The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
  • The class is final so we cannot create the subclass.
  • There is no setter methods i.e. we have no option to change the value of the instance variable.

These points makes this class as immutable.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience