How to create immutable class in Java?


An immutable class object's properties cannot be modified after initialization. For example String is an immutable class in Java. We can create a immutable class by following the given rules below −

  • Make class final − class should be final so that it cannot be extended.

  • Make each field final − Each field should be final so that they cannot be modified after initialization.

  • Create getter method for each field. − Create a public getter method for each field. fields should be private.

  • No setter method for each field. − Do not create a public setter method for any of the field.

  • Create a parametrized constructor − Such a constructor will be used to initialize properties once.

In following example, we've created a immutable class Employee.

Example

Live Demo
public class Tester{
   public static void main(String[] args){ 
      Employee e = new Employee(30, "Robert");
      System.out.println("Name: " + e.getName() +", Age: " + e.getAge());
   }
}

final class Employee {
   final int age;
   final String name;

   Employee(int age, String name){
      this.age = age;
      this.name = name;
   }

   public int getAge(){
      return age;
   }
   public String getName(){ 
      return name;
   }
}

Output

Name: Robert, Age: 30

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements