Part 14 / Topic 5 of 7
Records, recapped
A record (Java 16+, met in Stage 2) is an immutable data carrier: declare the components once, and the compiler writes the constructor, accessors, equals, hashCode and toString. Every permitted type in sections 1–4's sealed interfaces is a record, which is exactly what made record patterns possible — the compiler already knows each record's components by name and type.
Think of a pre-printed form with named, fixed fields: fill it in once, and anyone reading it already knows exactly which field is which, with no custom parsing.
A compact constructor runs before the fields are assigned, so it's the place to validate or normalize:
record Money(long paise) implements Comparable<Money> {
Money {
if (paise < 0) {
throw new IllegalArgumentException("paise cannot be negative, got: " + paise);
}
}
static Money ofRupees(long rupees, long extraPaise) { // static factory: reads better than new Money(...)
return new Money(rupees * 100 + extraPaise);
}
@Override public int compareTo(Money other) {
return Long.compare(this.paise, other.paise);
}
}
$ javac RecordsRecapDemo.java
$ java RecordsRecapDemo
-- construction, accessors, formatting --
price: Rs 1299.00 (paise=129900)
gst: Rs 233.82
total: Rs 1532.82
-- equals/hashCode/toString are generated, not written by hand --
price.equals(sameAsPrice): true
price == sameAsPrice: false
toString(): Money[paise=129900]
-- compact constructor validation --
rejected: paise cannot be negative, got: -50
-- Comparable, for sorting a cart --
Rs 99.50
Rs 499.00
Rs 1299.00
-- why this matters for sections 1-4 --
every permitted type in a sealed interface in this part is a record:
free equals/hashCode (useful in sets/maps), a compact constructor to validate,
and components the compiler already knows about -- which is exactly
what record patterns (section 4) deconstruct.
price.equals(sameAsPrice) is true even though price == sameAsPrice is false — the generated equals compares components (paise), not identity, exactly like String's equals versus == (Stage 1).
Full program: examples/RecordsRecapDemo.java.
Done here? The practice set for Part 14 — including the solutions — is on the part page.