Immutable Class

Immutable class, class whose state can not be changed.

Here state of class refers to the state of Object of class. Once we create Object of immutable class we can not change the state, other way, field of the Object.

Immutable classes are very much in use and one great example of immutable class is String.

How to create an immutable class ?

  1.  Restrict user of class from changing the field.  Don’t add setter methods in class to do so.
  2. Make all fields of class private and final so that any other method can not change the field.
  3. Restrict sub classes from overriding methods by making your class final which will stop other classes from extending your immutable class. (Because final class can not be extended in java)
  4. Fields of the class can be mutable. So, it’s better to create new instances of mutable fields in the constructor and copy the state. Better approach is to use factory method to have a single way to construct the object and make constructors private to avoid unplanned construction.

So by following above steps you can create an immutable class. Consider following example of immutable class,

public final class ImmutableDemo {

   private final int number;

   private ImmutableDemo(int number) {
      this.number = number;
   }

   public static ImmutableDemo getImmutableDemoInstance(int number) {
      return new ImmutableDemo(number);
   }

   public int getNumber(int number) {
      return number;
   }
}

As state of immutable class can not be changed, makes the immutable class thread safe which is one of the benefits of immutable classes.

It’ easy to construct and use in the application. Immutable classes are concrete and safe compared to mutable classes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s