Design your own immutable class
36 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)To make your own class immutable, close every door: no way in to change the fields after the constructor, and no way out for outside code to reach a mutable part of the object. A Rupees amount, a marksheet or a train ticket are good candidates.
The rules for an immutable class
An immutable class is a class whose objects can never change after construction. It is final, its fields are private final, it has no setters, it copies mutable inputs and outputs, and its "change" methods return new objects.
A Rupees amount should never change once it is made. Each rule closes one door: no child classes, no reassigned fields, no setters, no shared arrays.
Example 1 · An immutable Rupees class
final class Rupees { private final int amount;
Rupees(int amount) { this.amount = amount; }
int getAmount() { return amount; }
Rupees plus(Rupees other) { return new Rupees(amount + other.amount); }
@Override public String toString() { return "Rs. " + amount; }}
public class RupeesDemo { public static void main(String[] args) { Rupees price = new Rupees(500); Rupees gst = new Rupees(90); Rupees total = price.plus(gst); price.plus(gst); System.out.println(price + " + " + gst + " = " + total); }}Rs. 500 + Rs. 90 = Rs. 590
What this code does
final class, aprivate finalfield and no setter: once made, aRupeesobject never changes.plusreturns a new object; the secondprice.plus(gst)result is thrown away, andpricestays Rs. 500.
Fields that hold other immutable objects, like String or another immutable class of yours, need no copies: sharing them is safe. The next sections add the remaining rules one at a time.
Check the values once, in the constructor
The constructor is the only place where the fields get their values, so it is the one place to check them. If a value is wrong, throw IllegalArgumentException and the object is never made.
Example 2 · Validation in the constructor
final class Rupees { private final int amount;
Rupees(int amount) { if (amount < 0) { throw new IllegalArgumentException("Amount cannot be negative: " + amount); } this.amount = amount; }
Rupees minus(Rupees other) { return new Rupees(amount - other.amount); }
@Override public String toString() { return "Rs. " + amount; }}
public class ValidDemo { public static void main(String[] args) { Rupees balance = new Rupees(300); System.out.println(balance.minus(new Rupees(120))); try { Rupees bad = balance.minus(new Rupees(500)); System.out.println(bad); } catch (IllegalArgumentException e) { System.out.println("Refused: " + e.getMessage()); } System.out.println("Balance still " + balance); }}Rs. 180 Refused: Amount cannot be negative: -200 Balance still Rs. 300
What this code does
minusgoes through the constructor too, so a negative result is refused there; no invalidRupeescan exist.- The failed operation did not touch
balance: an immutable object cannot be left half-changed.
This gives a strong promise: every object of the class that exists is valid. Validating object state (opens in a new tab) guarded setters; here there are no setters left to guard, so one check is enough forever.
Order of execution
What happens on balance.minus(new Rupees(500))
Tap the steps in the order they happen.
Arrays need defensive copies
private final int[] marks stops the field from pointing elsewhere, but the array inside can still change. Read-only fields (opens in a new tab) showed the fix: copy in the constructor and in the getter.
Example 3 · Mistake: the array leaks in and out
import java.util.Arrays;
final class Marksheet { private final String name; private final int[] marks;
Marksheet(String name, int[] marks) { this.name = name; this.marks = marks; }
int[] getMarks() { return marks; }
@Override public String toString() { return name + " " + Arrays.toString(marks); }}
public class LeakDemo { public static void main(String[] args) { int[] input = { 72, 65, 80 }; Marksheet m = new Marksheet("Arjun", input); System.out.println(m);
input[0] = 99; m.getMarks()[1] = 99; System.out.println(m); }}Arjun [72, 65, 80] Arjun [99, 99, 80]
What this code does
- The constructor stored the caller's array, so
input[0] = 99changed the marksheet from outside. - The getter returned the inside array itself, so
getMarks()[1] = 99changed it too.finaldid not help.
Example 4 · The fix: defensive copies
import java.util.Arrays;
final class Marksheet { private final String name; private final int[] marks;
Marksheet(String name, int[] marks) { this.name = name; this.marks = Arrays.copyOf(marks, marks.length); }
int[] getMarks() { return Arrays.copyOf(marks, marks.length); }
@Override public String toString() { return name + " " + Arrays.toString(marks); }}
public class CopyDemo { public static void main(String[] args) { int[] input = { 72, 65, 80 }; Marksheet m = new Marksheet("Arjun", input);
input[0] = 99; m.getMarks()[1] = 99; System.out.println(m); }}Arjun [72, 65, 80]
What this code does
- The constructor keeps its own copy, so later changes to
inputdo not reach the object. - The getter hands out a fresh copy each time; changing it changes only that copy.
A field that holds one of your own mutable objects is copied the same way, with its copy constructor, deep enough that nothing inside is shared, as in Shallow vs deep copy (opens in a new tab).
Changes return new objects: with-methods
An immutable ticket still needs a new seat sometimes. A with-method, like withSeat("B2-14"), returns a new object with one value changed and every other value copied.
Example 5 · A Ticket with with-methods
final class Ticket { private final String passenger; private final String train; private final String seat;
Ticket(String passenger, String train, String seat) { if (passenger == null || passenger.isEmpty()) { throw new IllegalArgumentException("Passenger name needed"); } this.passenger = passenger; this.train = train; this.seat = seat; }
Ticket withSeat(String newSeat) { return new Ticket(passenger, train, newSeat); }
Ticket withTrain(String newTrain) { return new Ticket(passenger, newTrain, seat); }
@Override public String toString() { return passenger + " | " + train + " | " + seat; }}
public class TicketDemo { public static void main(String[] args) { Ticket booked = new Ticket("Kavya", "12951 Rajdhani", "WL-12"); Ticket confirmed = booked.withSeat("B2-14"); Ticket changed = confirmed.withTrain("12953 Kranti").withSeat("S4-31"); System.out.println(booked); System.out.println(confirmed); System.out.println(changed); }}Kavya | 12951 Rajdhani | WL-12 Kavya | 12951 Rajdhani | B2-14 Kavya | 12953 Kranti | S4-31
What this code does
- Each with-method copies every field into a new
Ticket, changing just one. The old tickets stay as they were. - With-methods return a
Ticket, so they can be chained likeStringmethods.
The caller must store the result: t = t.withSeat("B2-14");. Calling t.withSeat(...) alone changes nothing, exactly like s.toUpperCase().
Why the class must be final
If the class is not final, anyone can write a child class. The child can add a changeable field and override a getter to return it.
Example 6 · Mistake: a child class breaks a non-final class
class Rupees { private final int amount;
Rupees(int amount) { this.amount = amount; }
int getAmount() { return amount; }}
class SneakyRupees extends Rupees { int fake;
SneakyRupees(int amount) { super(amount); fake = amount; }
@Override int getAmount() { return fake; }}
public class SneakyDemo { public static void main(String[] args) { SneakyRupees sneaky = new SneakyRupees(100); Rupees price = sneaky; System.out.println(price.getAmount()); sneaky.fake = 1; System.out.println(price.getAmount()); }}100 1
What this code does
Rupeesis notfinal, so a child overridesgetAmount()and returns a field that can change.- Code holding a
Rupeesreference sees the price change from 100 to 1. Withfinal class Rupees,SneakyRupeeswould not compile.
With final class Rupees, SneakyRupees would not compile: cannot inherit from final Rupees. It is the same final class from final with inheritance (opens in a new tab), used here to protect a promise.
Find the bug
Find the open door
Select the line that is wrong.
A Team must not change when the caller edits their array.
Round 1 of 4Next step
Check your understanding
12 quick questions