
In Java, immutability is a key concept for writing thread-safe and predictable code. But how do you create an immutable class, and why is it so important? Letโs explore this with a practical example! What is an Immutable Class?
An immutable class is a class whose instances cannot be modified after they are created. This means that once an object is created, its state is set in stone, making it inherently thread-safe and easy to work with. How to Create an Immutable Class:
1. Make the class final: Prevents inheritance, so the behavior of the class canโt be altered.
2. Make all fields private and final: Ensures fields are initialized once and never changed.
3. Initialize all fields via a constructor: Set all properties during object creation.
4. Use deep copies for mutable fields: If the class has fields that hold references to mutable objects, return deep copies in getter methods.
5. No setter methods: Ensure the class does not provide any method that modifies fields after object creation.Example in Image :
Person Class: This class is immutable because:
No setters: The objectโs state cannot be altered once itโs created.
Final fields: The properties name and age are set once during construction and never changed.
Thread safety: Since the state cannot change, the object can be safely shared across threads without the risk of race conditions.
Java Records are a newer feature introduced in Java 14 (as a preview) and made permanent in Java 16. They offer a concise way to create immutable data classes, reducing boilerplate code significantly. Records are designed to model plain data aggregates with less code compared to traditional classes.
Key Features of Java Records:
Immutable by Default: Records are inherently immutable, meaning all fields are final and cannot be changed after the object is created.
Concise Syntax: A record automatically generates the constructor, getters, equals(), hashCode(), and toString() methods, which significantly reduces boilerplate code.
Data-Centric: Records are ideal for classes whose main purpose is to hold data. They emphasize the data being stored rather than the behavior.
Example:
Hereโs how you can define and use a simple Person record in Java:
๐ฉ๐ฎ๐๐ฅ๐ข๐ ๐ซ๐๐๐จ๐ซ๐ ๐๐๐ซ๐ฌ๐จ๐ง(๐๐ญ๐ซ๐ข๐ง๐ ๐ง๐๐ฆ๐, ๐ข๐ง๐ญ ๐๐ ๐) { }
