Creating an Immutable Class in Java
Join the DZone community and get the full member experience.Join For Free
In this article, we'll define the typical steps for creating an immutable class in Java and then implement it.
Steps to create Immutable class in java
- Make your class final, so that no other classes can extend it.
- Make all fields private so that direct access is not allowed.
- Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
- Special attention when having mutable instance variables
- Inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real instance passed through the constructor.
- Make sure to always return a clone copy of the field and never return the real object instance.
Implementation of Immutable class in java
Let's suppose that above we have a class called User, which we need to convert into an Immutable class in Java. Let's follow the rules and convert this User class into an Immutable class in java.
Pre-defined Immutable class in java
- The string class represents the immutable object for the sequence of characters.
- Wrapper classes like Integer, Float, Long, etc. all represent the immutable object for the corresponding primitive type.
java.util.UUIDrepresents a unique 128-bit hexadecimal string.
Benefits of making an Immutable class in java
- Immutable objects are by default thread-safe.
- Immutable objects can easily be cached.
- Immutable objects are the best options to use as a key object in any map like HashMap.
In this article, we have seen how to create an Immutable class in java. The immutable class provides us many advantages and best suited for multi-threaded environments. We also learn the rules to make an immutable class and its benefits.
Thanks for reading this article.
Published at DZone with permission of Shubham Bansal. See the original article here.
Opinions expressed by DZone contributors are their own.