0
0
JavaHow-ToBeginner · 3 min read

How to Create Immutable Class in Java: Simple Guide

To create an immutable class in Java, declare the class as final, make all fields private final, initialize them via constructor only, and provide no setters. Also, avoid exposing mutable objects directly by returning copies in getters.
📐

Syntax

To create an immutable class in Java, follow these steps:

  • Declare the class as final to prevent subclassing.
  • Make all fields private final so they cannot be changed after initialization.
  • Initialize all fields only once inside the constructor.
  • Do not provide any setter methods.
  • If fields are mutable objects, return copies in getter methods to prevent external modification.
java
public final class ImmutableClass {
    private final int value;
    private final String name;

    public ImmutableClass(int value, String name) {
        this.value = value;
        this.name = name;
    }

    public int getValue() {
        return value;
    }

    public String getName() {
        return name;
    }
}
💻

Example

This example shows a simple immutable class Person with two fields: name and age. The class is final, fields are private final, and only getters are provided.

java
public final class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        Person p = new Person("Alice", 30);
        System.out.println("Name: " + p.getName());
        System.out.println("Age: " + p.getAge());
    }
}
Output
Name: Alice Age: 30
⚠️

Common Pitfalls

Common mistakes when creating immutable classes include:

  • Not declaring the class final, allowing subclassing that can break immutability.
  • Using non-final fields that can be changed after construction.
  • Providing setter methods that modify fields.
  • Exposing mutable objects directly through getters without returning copies.

Here is a wrong and right way to handle mutable fields:

java
import java.util.Date;

// Wrong way: exposes mutable Date directly
public final class WrongImmutable {
    private final Date date;

    public WrongImmutable(Date date) {
        this.date = date;
    }

    public Date getDate() {
        return date; // exposes internal mutable object
    }
}

// Right way: returns a copy of Date
public final class RightImmutable {
    private final Date date;

    public RightImmutable(Date date) {
        this.date = new Date(date.getTime());
    }

    public Date getDate() {
        return new Date(date.getTime()); // returns copy
    }
}
📊

Quick Reference

Summary tips for creating immutable classes:

  • Use final class and private final fields.
  • Initialize all fields in constructor only.
  • Do not provide setters.
  • Return copies of mutable objects in getters.
  • Keep class simple and focused on immutability.

Key Takeaways

Declare the class as final to prevent subclassing.
Make all fields private and final to prevent modification.
Initialize fields only once in the constructor.
Do not provide setter methods to change fields.
Return copies of mutable objects to keep immutability.