Immutable class in java

Let’s learn immutable class in java.

Immutable class in java

An immutable object in one that once the object is created its state or content cannot be modified.

For example: string is immutable in java. Click here to know why. Also all wrapper classes namely Boolean, Byte, Short, Integer, Long,  Float, Double etc are immutable.

Let’s see how to create immutable class or how to write immutable class.

  • To create an immutable class, declare it as “final”. Because an immutable class should not extend or shouldn’t be able to create child classes.
  • All the fields or data members in an immutable class should be declared with access modifier “private”. This will ensure all fields are not accessed outside the class.
  • Assign values to data members or initialize all data members through parametrized constructor to perform deep copy. Deep copy ensures data members aren’t modified.
  • Deep copy should be performed in getter methods to return copy.
  • No setter methods. Because setter methods are used to change the value of instance variable.

Now let’s see immutable class with example or create custom immutable class.

public final class EmployeeDetails
{  
   final String aadharNumber;  
   public EmployeeDetails(String aadharNumber)
   {
      this.aadharNumber = aadharNumber;  
   }  
   public String getAadharNumber()
   {
      return aadharNumber;  
   }      
}