Pages

How to write an immutable Class in Java

Immutable Class ?

Immutable classes  are those classes whose instances  state doesn’t change after it has been initialized.

As we know that in Java String is an immutable class and once instantiated its value never changes.

Immutable object once created and initialized that can not be changed so these objects are the right candidate for the caching and it is also thread-safe , so you don't worry about thread safety.


Here I am providing a way to create immutable class via an example for better understanding.

To create a class immutable, you need to follow following steps:
  1. Declare the class as final so it can’t be extended. so overriding of method is not possible.
  2. all fields must private and final, so that direct access is not allowed and once the value of field initialized they can't be changed.
  3. Don’t provide setter methods for variables
  4. Make all mutable fields final so that it’s value can be assigned only once.
  5. Initialize all the fields via a constructor performing deep copy.
  6. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.



public final class ImmutableStudent {

 // field once intialized can not be changed 
 final String name;
 final int regNo;

 public ImmutableStudent(String name, int regNo) {
  this.name = name;
  this.regNo = regNo;
 }

 public String getName() {
  return name;
 }

 public int getRegNo() {
  return regNo;
 }
 
 // No setter method 
 
}
The static factory method implementation for immutable class--
public class ImmutableStudentFactory {

 final private String name;
 final private int age;

 // private constructor so no class extend this
 private ImmutableStudentFactory(final int age, final String name) {
  this.age = age;
  this.name = name;
 }

 // static factory method
 public static ImmutableStudentFactory getInstnace(final int age,
   final String name) {
  return new ImmutableStudentFactory(age, name);
 }

 public int getAge() {
  return age;
 }

 public String getName() {
  return name;
 }

No comments:

Post a Comment