How to Create Immutable Objects in Java

Immutable objects pattern is one of the creational patterns. If you have to create read-only objects that can be shared and used by multiple classes then making the objects immutable will be a good pattern choice.

Motivation: If you want to create objects that can be shared across multiple classes, but for some security reasons you don’t want their value to be modified. You could copy the object before sending it to another method, but that would duplicate the object every time it is passed. And if you have multiple threads accessing the same object,  you could run into concurrency issues.

Solution: Creating objects whose state does not change after they are created.

Implementation: A common way to create an immutable object is by following these steps:

  1. Use a constructor for setting all the properties of the object.
  2. Mark all the instance variables as private and final.
  3. Don’t define any setters.
  4. Don’t allow any referenced mutable objects to be modified or accessed directly.
  5. prevent methods from being overridden.

An example of an immutable Book class:

public final class Book {
    private final String genre;
    private final int totalPages;
    private final List<String> authors;
 
    public Book(String genre, int totalPages, List<String> authors ){
        this.genre = genre;
        this.totalPages = totalPages;
        if(authors == null){
            throw new RuntimeException("The author is required");
        }
        this.authors = new ArrayList<>(authors);
    }

    public String getGenre() {
        return genre;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public String getAuthor(int index) {
        return authors.get(index);
    }
}

 

Leave Comment

Your email address will not be published. Required fields are marked *