Sobes.tech
Junior — Middle

How can an immutable object be implemented in programming?

sobes.tech AI

Answer from AI

An immutable object is an object whose state cannot be changed after creation. In Java, this is achieved through several methods:

  1. Declare the class as final — so it cannot be subclassed and behavior cannot be altered.
  2. Make all fields private and final — so their values cannot be changed after initialization.
  3. Do not provide setters — only getters for accessing fields.
  4. Initialize all fields through the constructor.
  5. If a field is a reference type, ensure its immutability (for example, by using immutable collections or creating copies of objects when passing them).

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

Thus, once a Person object is created, its state cannot be changed.

How can an immutable object be implemented in… - sobes.tech