What makes a Java Object Immutable
Immutability is a powerful tool in creating highly concurrent, thread-safe applications.
Everything you need to consider is within the code below.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// 1. mark the class as final to prevent it from being extended
public final class ImmutableExample {
// 2. mark all instance variables as private and final so they cannot be changed outside of constructor
private final String myVariable;
private final Integer myOtherVariable;
private final List<String> myList;
// 3. Everything set via constructor
public ImmutableExample(String myVariable, Integer myOtherVariable, List<String> myList) {
this.myVariable = myVariable;
this.myOtherVariable = myOtherVariable;
// 4. collections need to be copied so no references outside of this class can make changes
this.myList = new ArrayList<>(myList);
}
// 5. implmenent getters only!
public String getMyVariable() {
return myVariable;
}
public Integer getMyOtherVariable() {
return myOtherVariable;
}
public List<String> getMyList() {
// 6. return a read only version of the collection or a copy so external references cant make changes
return Collections.unmodifiableList(myList);
}
}