Java Immutable Class - Builder Pattern With Examples

In my last post, I explained about Builder Pattern in Java. Sometime back I wrote an article about how to create immutable class in java. In this post, we will learn how easy it’s to create java immutable class using Builder pattern. Using builder pattern to create immutable class is a good approach when the number of arguments in the Constructor is more that can cause confusion in their ordering.

Java Immutable class important points

  • The immutable class should have only getter methods.
  • The immutable class will have a private constructor with Builder object as parameter that will be used to create the immutable class.
  • If the immutable class attributes are not immutable, for example HashMap, we should perform deep copy or cloning to avoid modification of its attributes.
  • Using Builder pattern is easy when number of optional attributes are more in the immutable class.

Java Immutable Class – Builder Pattern

Here is the implementation of an immutable class in java using Builder pattern.

Here is the test program to check if the object we create is immutable or not.

That’s all for creating immutable class in java using builder pattern.

Reference: Oracle Documentation

By admin

Leave a Reply

%d bloggers like this: