Sobes.tech
Junior — Middle

Milliseid põhimõtteid tuleks kasutada Java klassi loomisel, et muuta see muutumatuks?

sobes.tech AI

Vastus AI-lt

To make a class in Java immutable, several principles must be followed:

  1. Declare the class as final — so that it cannot be subclassed, which could alter its behavior.
  2. Make all fields private and final — so that they cannot be changed after initialization.
  3. Do not provide setters (methods to modify fields).
  4. Initialize all fields through the constructor.
  5. If fields are references to mutable objects (e.g., arrays, collections), create copies of them during assignment and when returning from getters, so external changes do not affect internal state.

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

Such a class, after creating an object, does not allow changing its state, which is useful for thread safety and predictable behavior.