Cover Image for Creating Immutable class
185 views

Creating Immutable class

The immutable class in Java is a class whose instances cannot be modified once they are created. In other words, the state of an immutable object remains constant throughout its lifetime. To create an immutable class, you need to follow certain guidelines and apply specific practices:

  1. Make the Class Final: To prevent the class from being extended or subclassed, declare it as final. This ensures that no one can create a subclass that might introduce mutable behavior.
  2. Declare Fields as Final: Make all the fields in the class final. This ensures that the fields’ values cannot be changed once they are set in the constructor.
  3. Private Fields: Make the fields private to restrict direct access to them. Access to the fields should be controlled through getter methods.
  4. No Setter Methods: Avoid providing setter methods that can modify the fields. Immutable objects should not have methods that change their state.
  5. Initialize Fields in the Constructor: Initialize all fields in the constructor. Ensure that the constructor receives all necessary data to set the object’s state at the time of creation.
  6. Defensive Copy: If the class stores mutable objects (e.g., collections or arrays), make a defensive copy of these objects to prevent external changes. This ensures that the internal state remains constant.
  7. No Mutable Return Types: Avoid returning references to mutable objects. If your class returns an object, make sure it is an immutable or read-only view of the data.
  8. **Override equals() and hashCode(): If the class is expected to be compared or used as a key in collections, override the equals() and hashCode() methods. Ensure that the implementation is consistent with the class’s immutability.
  9. Thread-Safety: Ensure that your immutable class is thread-safe, meaning that it can be safely accessed and used by multiple threads without the risk of concurrent modification issues. This often involves proper synchronization in methods if the class contains shared mutable data.

Here’s an example of creating an immutable class:

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ImmutablePerson that = (ImmutablePerson) o;

        if (age != that.age) return false;
        return name != null ? name.equals(that.name) : that.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

ImmutablePerson is a simple immutable class with two fields (name and age), which are made final and initialized in the constructor. The class is final to prevent subclassing, and it provides getter methods to access the fields. The equals() and hashCode() methods are also overridden to ensure correct behavior when used in collections.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS