31 How to create an immutable class in Java?

What is immutable class?

  • An object is immutable if it cannot be change after initializing
  • Because, immutable object can not be changed, every time we try to update the information in that class,
    –> Actually , we have create another object and it change the copied object( not original object)

What is the advantage of immutable class?

  • An immutable object is good for caching purpose, because you don’t worry about the value change
  • Immutable class support thread safe in mutiple thread

How can we create immutable class

There are some conditions if we want to an immutable class:

  • Keep class is private so it can not be inherited
  • Make all the field of class is private so it can not be access directly
  • Don’t provide setter method for variable Initialize all the field in a constructor performing deep copy
  • when you manipulate with the object, you return a copy object using construct rather than return the actual object reference
  • More convinent, you can use builder pattern to create immutable class

Leave a Reply

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