How to create an immutable class in Java?

  1. Declare the class final (no subclass can break it).
  2. Make all fields private final.
  3. Do not write setters.
  4. Set all fields in the constructor.
  5. For mutable fields (like a list or a date) make a defensive copy when you get it and when you return it.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    static final class Team {
        private final String name;
        private final List<String> members;

        Team(String name, List<String> members) {
            this.name = name;
            this.members = List.copyOf(members);           // copy in
        }

        String name() { return name; }
        List<String> members() { return members; }          // List.copyOf is already unmodifiable
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("Riya", "Aman"));
        Team t = new Team("Java", list);
        list.add("Hacker");                                 // does not change the team
        System.out.println(t.members());
        try {
            t.members().add("Another");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot change the members");
        }
    }
}
Output

[Riya, Aman]
Cannot change the members

A record is the shortest way, if you only need the data and you copy the mutable parts yourself. See Java Records.


Learn more about the similar topics:
Tutorials
Java Classes and Objects
Java Constructors
Java static and this Keywords
Java Encapsulation and Access Modifiers
Java Inheritance
Java Polymorphism
Java Abstract Classes
Exercises & Assignments
Build a BankAccount class
Calculate areas with inheritance and polymorphism
Use a sealed interface and pattern matching
Interview Questions & Answers
What is a class and an object in Java?
What is a constructor in Java?
What is the difference between a constructor and a method in Java?
What is the this keyword in Java?
What is the static keyword in Java?
What is the final keyword in Java?
What are the four pillars of OOP in Java?