What makes a Java class immutable, and what are the rules you have to follow?
An immutable object is one that can never change after it has been made. Once the constructor has finished, the object always holds exactly the same values for the rest of its life.
There are four rules, and you have to follow all four.
The first rule is that every field is private final. Private so that nobody outside the class can change it, and final so that the class itself cannot change it after the constructor has run.
The second rule is that there are no methods that change the object. No setters, and no other method that writes to a field.
The third rule is that the class is final. This one is easy to forget, and it matters. If the class can be extended, then a subclass could add a field and a setter, and the object would not really be immutable any more.
The fourth rule is that a field which points at something mutable must be copied when it goes in and when it comes out. Otherwise somebody could reach through your object and change the thing inside it.
public class Main {
public static void main(String[] args) {
Money money = new Money(1050, "GBP");
System.out.println("the amount : " + money.getAmount());
System.out.println("the currency: " + money.getCurrency());
// There is no way to change it, because there is no setter.
System.out.println("there is no setter, so the value cannot change");
}
}
final class Money {
private final int amountInMinorUnits;
private final String currency;
Money(int amountInMinorUnits, String currency) {
this.amountInMinorUnits = amountInMinorUnits;
this.currency = currency;
}
int getAmount() {
return this.amountInMinorUnits;
}
String getCurrency() {
return this.currency;
}
}
The next question in this topic looks at the fourth rule, which is the one that catches people out.