Category Archives: Core Java

Immutable Classes

What are immutable classes?

Immutable classes are those whose state cannot be changed after construction.

E.g. String is an immutable class in Java and so is Integer. BigDecimal isn’t.

How do we create an immutable class?

a) Make the class final (This means that we cannot extend the class to create a subclass)

b) Do not have a default constructor (That means no one can do a new ClassA() of the class). Instead, like the singleton pattern implementation, have a static method to get the instance of the class or have constructors with inputs in them.

c) Do not allow any methods (accessors i.e setters/getters) which will change the state of the object.

d) Have exclusive access to mutable fields. That means in the getter method which might return the existing field of the object, return a new object.

What are the properties of an immutable class?

a) Automatically thread-safe (no synchronization required) in nature (so all the threading issues are resolved) and cannot be extended.

b) Don’t have to handle clone(). And we can do a lazy initialization of hashCode()

c) have failure atomicity (which means that if this immutable object throws an exception it will not be left in an indeterminate state)

d) Helps in having a stable and fault tolerant system

e) They make for good Map and Set elements as the key elements in these collections should never change while in the collection.

The main issue with immutables: Too many objects lying around. 

Example code (from Marcus Biel’s website):

public final class ImmutableSpaceship {
    private final String name;
    private final Destination destination;
 // Note: There is no default constructor.
    public ImmutableSpaceship(String name) {
        this.name = name;
        this.destination = new Destination("NONE");
    }
    
    private ImmutableSpaceship(String name, Destination destination) {
        this.name = name;
        this.destination = new Destination(destination);
    }
  
    public Destination currentDestination() {
        return new Destination(destination);
    }
    public ImmutableSpaceship newDestination(Destination newDestination) {
        return new ImmutableSpaceship(this.name, newDestination);
    }
[…]
}

References:
https://marcus-biel.com/immutables-in-java/
http://www.javapractices.com/topic/TopicAction.do?Id=29