Sub topic 13
Designing Immutable Objects
An immutable object is an object whose state cannot change after it is created. Its state is the information stored in its fields, or variables that belong to the object.
Immutable objects are useful when several parts of a program need the same information. They can share the object without worrying that one part will change it. To use different values, you create a new object instead.
Build an immutable study plan
A class is a definition for a kind of object. The StudyPlan class below stores a learner’s name, the number of study minutes, and a list of topics.
A list is a collection of items in a set order. Lists need special care: many lists can be changed after they are created.
Save this code as StudyPlan.java. It needs Java 11 or newer.
import java.util.ArrayList;
import java.util.List;
final class StudyPlan {
private final String learner;
private final int minutes;
private final List<String> topics;
StudyPlan(String learner, int minutes, List<String> topics) {
if (learner == null || learner.isBlank()) {
throw new IllegalArgumentException("Learner needs a name");
}
if (minutes <= 0) {
throw new IllegalArgumentException("Minutes must be positive");
}
this.learner = learner;
this.minutes = minutes;
this.topics = List.copyOf(topics);
}
int getMinutes() {
return minutes;
}
List<String> getTopics() {
return topics;
}
StudyPlan withMinutes(int newMinutes) {
return new StudyPlan(learner, newMinutes, topics);
}
public static void main(String[] args) {
List<String> sourceTopics = new ArrayList<>(List.of("Java"));
StudyPlan first = new StudyPlan("Lee", 20, sourceTopics);
sourceTopics.add("Math");
StudyPlan second = first.withMinutes(30);
System.out.println(first.getTopics());
System.out.println(first.getMinutes());
System.out.println(second.getMinutes());
}
}Compile and run it:
javac StudyPlan.java
java StudyPlanThe output is:
[Java]
20
30Adding Math to sourceTopics does not change the topics in first. Also, withMinutes(30) creates a second plan. The first plan still has 20 minutes.
How the design protects state
The class uses several protections together:
privatemeans code outsideStudyPlancannot directly access its fields.finalon a field means that field can be assigned only once.finalon the class means another class cannot extend it and add different behavior.- There are no methods that change the fields after creation.
A method is a named set of instructions. The methods getMinutes and getTopics are getters: they let other code read values without replacing the fields.
A constructor is the part of a class that sets up a new object. The StudyPlan constructor checks its inputs before storing them. This check is called validation. A blank name or a nonpositive number of minutes causes an exception, which is Java’s way of reporting an error.
The topics list must also be non-null and contain no null items. List.copyOf rejects either case.
Protect lists and other objects
A field can hold a reference, which is a value that points to an object. The topics field holds a reference to a list.
Making a reference field final does not freeze the object it points to. If the constructor simply stored the caller’s changeable list, the caller could still add items to that list.
Instead, List.copyOf(topics) gives the plan an unmodifiable list with the items supplied at construction. A caller cannot add to or remove items from the list returned by getTopics.
Creating a new plan for each change can use more memory than changing an existing object. In return, the old plan stays safe to share and easy to reason about.
Exercise
Exercise
What happens to first when first.withMinutes(45) is called? What happens if the new minutes value is 0?
Show answer
The call creates a new plan with 45 minutes; first still has 20. A value of 0 causes an IllegalArgumentException, and first remains unchanged.