Immutability in Java

This article will help you to understand concept of Immutability in java.

What is Immutable class?

An immutable class is simply a class whose instances cannot be modified once it is creates. Immutable class takes all the information at a time of object creation and all this information is fixed for entire lifetime of object.

All wrapper classes in java.lang package are immutable. E.g. String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.

Benefit’s of using Immutability

  • Immutable Objects are inherently Thread safe, they require no synchronization since they cannot be changed once created.
  • Immutable Objects won’t face an issue of inconsistent object state, as they cannot be changed once created.
  • Immutable objects can be used as key in Map’s.

How to write immutable class?

To make class immutable follow these five rules

  1. Don’t provide any method that modifies the object’s state:

Don’t provide setter methods

  1. Ensure that class cannot be extended

Declare class as final so sub classing is not possible.

  1. Make all the fields Final.

Final fields can be modified in constructor or instance initializer block.

  1. Make all the fields private.

This prevents clients from obtaining access to mutable objects referred to fields and modifying these    objects directly.

  1. Ensure exclusive access to any mutable components.

If your class has any field that refers to mutable objects ensure that client of class cannot obtain   references to these objects. Never initialize such a field to client provided object reference or return the object reference from an accessor.

Let’s create  Person class with name, city and mutable object birthDate as shown below

Immutable class

Client class

Client class which will use immutable person class as given below

Output of client program.

The only real disadvantage of immutable classes is that they require a separate object for each distinct value. Immutable objects make great building block for other objects.

Happy learning!

1 thought on “Immutability in Java”

Leave a Reply

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