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 make a class immutable create a public class and 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 to initialize all data members through parametrized constructor.
  • setter methods are not allowed. Because setter methods are used to modify the value to set the value.

Now let’s see immutable class in java 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;  
   }      
}