Sobes.tech
Junior

What are immutable classes in Java?

sobes.tech AI

Answer from AI

An immutable class in Java is a class whose objects cannot be changed after creation.

Rules for creating an immutable class:

  1. The class should be declared as final to prevent inheritance and modification of behavior by subclasses.
  2. All fields should be declared as final so they cannot be changed after initialization.
  3. All fields should be declared as private to prevent direct access from outside.
  4. Do not provide setter methods.
  5. If the class contains mutable fields, such as List, they should be copied in the constructor and when returned from getter methods (defensive copy).
  6. Do not provide methods that can change the state of the object.

Advantages of immutable classes:

  • Thread safety: multiple threads can safely access the same object without synchronization.
  • Caching: immutable objects are easy to cache, improving performance.
  • Ease of debugging and testing: the state of the object is predictable.
  • Use as keys in associative collections (Map, Set).

Example of an immutable class:

final class ImmutableExample {

    private final String name;
    private final int value;
    private final List<String> tags;

    public ImmutableExample(String name, int value, List<String> tags) {
        this.name = name; // Primitives and String are immutable
        this.value = value;

        // Defensive copying of mutable field in constructor
        this.tags = new ArrayList<>(tags);
    }

    public String getName() {
        return name;
    }

    public int getValue() {
        return value;
    }

    public List<String> getTags() {
        // Defensive copying when returning mutable field
        return new ArrayList<>(tags);
    }

    // No setters or methods that change state
}