Immutability · Topic 2 of 6
Immutable class
Definition​
An immutable class creates objects that never change. Make the class final, make all fields private final, set them in the constructor, and give no setters. Methods that "change" the object return a new one.
Example code​
A Money class where plus() returns a new object
final class Money {
private final long amount;
private final String currency;
Money(long amount, String currency) {
this.amount = amount;
this.currency = currency;
}
Money plus(Money other) {
if (!currency.equals(other.currency)) throw new IllegalArgumentException("Different currencies");
return new Money(amount + other.amount, currency); // a new object, the old ones stay unchanged
}
@Override public String toString() { return amount + " " + currency; }
}
class Demo {
public static void main(String[] args) {
Money a = new Money(500, "INR");
Money b = new Money(250, "INR");
Money total = a.plus(b);
System.out.println(a + " + " + b + " = " + total);
System.out.println("a is still " + a);
}
}
// Output:
// 500 INR + 250 INR = 750 INR
// a is still 500 INR
Finished this page? Track your progress (saved only in your browser).