How to create Immutable class in Java?

Posted on Updated on

In Java there are many immutable classes are available. For example String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable.

Below are some points we have to follow while creating custom immutable class.

  1. Class should be final.
    By making class final, we can’t create subclass. So, methods can’t be override.
  2. Instance variable should be private and final.
    variable declared private will not be accessible outside the class and making them final insure that we can’t change it.
  3. Don’t provide “setter” methods.
    Setter methods are meant to change the state of the object. there are no setter methods, so we can’t change the state of the object.

The below example demonstrate creation of immutable class.

Employee is immutable because.

  1. The class is final, so we can’t create subclass.
  2. Instance variable “id” is final and private. So, we can’t change the value once created.
  3. There is no setter method. So, we can’t change the state of variable.

One thought on “How to create Immutable class in Java?

    Pratik said:
    February 22, 2016 at 7:09 pm

    Nice Article !!

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.