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.