How to create immutable class in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 03-Dec-2018 07:43:06
Advertisements