How to Create an Immutable Class in Java
An immutable object is an object whose state cannot be changed after it is created.
Once created:
-
values never change
-
no setters
-
no side effects
๐ง What Is Immutability?
Immutability means object state cannot be modified after construction.
Example (Already Immutable)
✔ String is immutable
✔ A new object is created instead of modifying the old one
๐ฏ Why Immutability Is Important
-
Thread-safe by default
-
No synchronization needed
-
Easier to reason about
-
Fewer bugs
-
Safer in functional programming
Used heavily in:
-
concurrency
-
caching
-
security-sensitive code
-
functional programming
✅ Rules to Create an Immutable Class
To make a class immutable in Java, follow these 5 rules:
1️⃣ Make the Class final
Prevents subclassing and modification.
2️⃣ Make All Fields private and final
Prevents modification after initialization.
3️⃣ Initialize Fields Using Constructor Only
No default modification allowed.
4️⃣ Do NOT Provide Setter Methods
Setters break immutability.
❌ setName()
❌ setId()
5️⃣ Defensively Copy Mutable Fields
Very important for collections and mutable objects.
๐งฉ Complete Immutable Class Example
๐งช Why Defensive Copy Is Required
❌ Without Defensive Copy (Broken Immutability)
✅ With Defensive Copy
-
Internal state remains unchanged
-
External modifications are blocked
๐ Testing Immutability
✔ Immutable object protected
๐งฑ Immutable Object Creation Pattern
๐ญ Real-World Examples of Immutability in Java
Built-in immutable classes:
-
String -
Integer,Long,Double -
LocalDate,LocalDateTime -
Path -
UUID
⚡ Immutable Objects & Thread Safety
Immutable objects are thread-safe by default because:
-
no state changes
-
no race conditions
-
no synchronization needed
๐ Mutable vs Immutable (Quick Comparison)
| Feature | Mutable | Immutable |
|---|---|---|
| State change | Allowed | ❌ Not allowed |
| Thread safety | Needs sync | Built-in |
| Complexity | Higher | Lower |
| Performance | May vary | Often better |
๐ฏ Interview-Ready Answer
An immutable class in Java is a class whose objects cannot be modified after creation.
It is created by making the class final, fields private and final, initializing them via constructor, avoiding setters, and using defensive copying for mutable fields.
๐ One-Line Summary
Immutability means creating objects whose state never changes after construction.
๐ Final Takeaway
If your object represents data, make it immutable.
If it represents behavior, mutability may be acceptable.
No comments:
Post a Comment