Sobes.tech
Junior — Middle

How to implement a class whose properties cannot be changed after creating an object?

sobes.tech AI

Answer from AI

To create a class in Java whose objects cannot be modified after creation (immutable), you need to:

  1. Declare the class as final (to prevent inheritance and behavior modification).
  2. Make all fields private and final.
  3. Do not provide setters (methods to modify fields).
  4. Initialize all fields through the constructor.
  5. If fields are references to mutable objects, create copies of them when assigning and returning (to avoid external modifications).

Example:

public final class ImmutablePerson {
    private final String name;
    private final int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

This class guarantees that once an object is created, its state will not change.

How to implement a class whose properties cannot be… - sobes.tech