How to Create an Immutable Class in Java

 

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 s = "Java"; s.concat(" World"); System.out.println(s); // Java (unchanged)

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.

public final class User { }

2️⃣ Make All Fields private and final

Prevents modification after initialization.

private final int id; private final String name;

3️⃣ Initialize Fields Using Constructor Only

No default modification allowed.

public User(int id, String name) { this.id = id; this.name = name; }

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

import java.util.List; import java.util.ArrayList; import java.util.Collections; public final class Employee { private final int id; private final String name; private final List<String> skills; public Employee(int id, String name, List<String> skills) { this.id = id; this.name = name; // defensive copy this.skills = new ArrayList<>(skills); } public int getId() { return id; } public String getName() { return name; } public List<String> getSkills() { // return unmodifiable copy return Collections.unmodifiableList(skills); } }

๐Ÿงช Why Defensive Copy Is Required

❌ Without Defensive Copy (Broken Immutability)

skills.add("Hacking"); // modifies internal state

✅ With Defensive Copy

  • Internal state remains unchanged

  • External modifications are blocked


๐Ÿ” Testing Immutability

List<String> skills = new ArrayList<>(); skills.add("Java"); Employee e = new Employee(1, "Vinod", skills); skills.add("Python"); // does NOT affect Employee e.getSkills().add("Go"); // throws exception

✔ Immutable object protected


๐Ÿงฑ Immutable Object Creation Pattern

new Object(...) ↓ State fixed forever ↓ Read-only access

๐Ÿญ 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)

FeatureMutableImmutable
State changeAllowed❌ Not allowed
Thread safetyNeeds syncBuilt-in
ComplexityHigherLower
PerformanceMay varyOften 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

Java Design Patterns With What • Why • When • Full Java Programs • Client Usage

  Java Design Patterns  With What • Why • When • Full Java Programs • Client Usage Introduction Design Patterns are proven solutions to...

Featured Posts