Immutable Objects in Java

Reading Time: 2 minutes

Immutable objects are those which, once initialized can not be changed. These kinds of objects are generally used as configuration objects or as constants. Immutable objects have advantages. These objects by default are thread safe, thus they don’t need to be synchronized. Also, they can be used in maps and sets without worrying about the repercussions of modifications.

Below are the things to consider while defining immutable classes.

  1. class should be final, so that it can not be extended later to introduce mutability by adding more variables.
  2. fields must be final, so that they can not be reassigned.
  3. Any objects passed as parameter to constructor, should be cloned before being assigned. Reason being, if the parameter object is referenced by some other part of code, it could still change the state of that object.
  4. Class should not provide any setter methods.
  5. All the getter methods should only return deep copy of the object. If any of the getter is supposed to return a collection, it should return an unmodifiable copy of the collection.

Below is a example of immutable class

class Address {
	private String address;

	Address(String address) {
		this.address = address;
	}

	public String getAddress() {
		return address;
	}
}

final class Immutable {
	private final int id;
	private final String name;
	private final Address primaryAddress;
	private final List<Address> addresses;

	Immutable(int id, String name, Address primaryAddress, List<Address> addresses) {
		this.id = id;
		this.name = name;
		this.primaryAddress = new Address(primaryAddress.getAddress());
		this.addresses = Collections.unmodifiableList(addresses)
	}

	public int getId() { 
	    return id; 
    }

	public String getName() { 
	    return name; 
	}

	public Address getPrimaryAddress() { 
	    return new Address(primaryAddress.getAddress()); 
	}

	public List<Address> getAddresses() { 
	    return addresses; 
	}
}