Sobes.tech
Senior

What is an immutable object and how to create it?

sobes.tech AI

Answer from AI

An immutable object is an object whose state cannot be changed after creation. In Java, this is important for thread safety and predictability.

To create an immutable class:

  1. Make the class final so it cannot be subclassed and behavior cannot be changed.
  2. All fields should be private and final.
  3. Do not provide setters.
  4. Initialize all fields through the constructor.
  5. If fields are objects, ensure they are also immutable or make deep copies when passing and returning.

Example:

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;
    }
}