How to make Java class immutable?

What is immutable class?

Immutable java class means its state cannot be changed. Generally the state of the class is determined by its fields or properties. There are certain ways by which we can prevent the state of a class to be unchanged which is explained in detail further.

When do we need to make class immutable?

  • The immutable class objects can be used as Map keys and Set elements as these objects should not change their state.
  • Don’t need explicit cloning implementation and can directly be returned.
  • These objects are good for caching as their states are constant and their is no problem of stale data.

How to make a class Immutable in Java?

  • Don’t declare setter methods : The setter methods usually changes the state of the field. So to avoid that for immutability, the setter methods should not be declared in immutable class.
  • Declare fields as private and final: private fields can’t be accessed from outside the class and final will restrict the fields from being modified after creation.
  • Declare the class as final: By declaring class as final, subclasses cannot be created. This will restrict the overriding of any method and in turn no modification from child class is possible.
  • Return cloned object from getter methods for mutable objects inside class: This is a special case where the immutable class contains references of mutable object. To avoid the state of mutable object to be changed, return the clone of the object from getter methods rather than actual reference.
  • Avoid sharing reference of mutable object: Instead of sharing actual reference, share the copy of the reference object so that any change in the state will not affect the original object.

Lets take an example to understand it completely:

final class Employee {
   private final int id;
   private final String name; 
   private final int age;
   private final Address address;
   private final List<String> employers
   public Employee(int id, String name, int age, Address address, ) {
      super();
      this.id
      this.name = name;
      this.age = age;
      this.address = address;
   }
   public String getId() {
      return id;
   } 
   public String getName() {
      return name;
   }
   public int getAge() {
      return age;
   }
   // Special handling for mutable objects inside class
   public Address getAddress() throws CloneNotSupportedException {
      return (Address) address.clone();
   }
   public List<String> getEmployers() { //return  employers ; 
      return (List<String>)  employers.clone(); 
   } 
}

For list to be made immutable you can refer how to make a list immutable.

Leave a Comment

Your email address will not be published. Required fields are marked *