Sobes.tech
Middle

How to write an immutable class in Java?

sobes.tech AI

Answer from AI

To make a class immutable in Java, follow these principles:

  1. Make the class final so it cannot be subclassed and its behavior cannot be changed.
  2. Make all class fields private and final so they cannot be modified after object initialization.
  3. Do not provide setter methods.
  4. If the class contains mutable fields (e.g., List or Date), return copies of these objects in getters instead of references to the original objects. Also, accept copies of mutable objects in the constructor.
  5. Override equals() and hashCode() methods if necessary for correct object comparison and collection operations.

Example:

// Final class to prevent inheritance
public final class ImmutablePerson {

    // Private final fields
    private final String name;
    private final int age;
    private final List<String> achievements;

    // Constructor initializing all fields.
    // Creates copies of mutable fields.
    public ImmutablePerson(String name, int age, List<String> achievements) {
        this.name = name;
        this.age = age;
        // Creating a copy of the mutable list
        this.achievements = new ArrayList<>(achievements);
    }

    // Getters returning field values.
    // Return copies for mutable fields.
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public List<String> getAchievements() {
        // Return a copy of the list to prevent external modification
        return new ArrayList<>(achievements);
    }

    // Override equals and hashCode (optional but often necessary)
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ImmutablePerson that = (ImmutablePerson) o;
        return age == that.age &&
               Objects.equals(name, that.name) &&
               Objects.equals(achievements, that.achievements);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, achievements);
    }
}

This class guarantees that once an object is created, its state (field values) cannot be changed. This provides advantages in multithreading, security, and simplifies development.

How to write an immutable class in Java? — Java - sobes.tech