Create An Immutable Class In Java
Learn about how to create an Immutable class in java and its benefits.
Published in
6 min readJul 24, 2021
Table of Contents
- Overview
- Usage of Immutable class
- Steps to create an Immutable class
- Exploring Existing Immutable classes in Java
- Examples with/without Mutable/Immutable class
- Conclusion
1. Overview
Immutable class, once an object is instantiated, we cannot modify its content. In Java, all the wrapper classes (let’s say, Integer, Short, Boolean, Byte, etc.) and String, etc. classes — are immutable. We can create our own immutable class as well.
An object is immutable if its state cannot be modified after construction. Immutable objects don’t expose any way for other objects to modify their state; the object’s fields are initialized only once inside the constructor and never change again.[³]
Always remember that,
- Primitive data types — includes byte, short, int, long, float, double, boolean, and char.
- Non-primitive data types — such as String, Arrays, Interfaces, and Classes.