Chapter 19Part VI · Modern Java
Data-Oriented Java: Records, Sealed Types and Patterns
In this chapter: how three features from Java 16–21 work together. Records hold data, sealed types close a hierarchy, and pattern matching takes data apart safely. Together they replace a lot of Java 7 visitor-pattern and
instanceof-chain code.
Key points
- Records (Java 16): immutable data carriers with generated constructor, accessors,
equals,hashCodeandtoString. Validate in a compact constructor. - Sealed interfaces (Java 17): a closed set of alternatives, such as
Card,UpiorCash. - Record patterns (Java 21) deconstruct records in
switchandinstanceof:case Card(String last4, long cents). - Over a sealed type,
switchis exhaustive: nodefault, and adding a new alternative becomes a compile error everywhere it's unhandled. _(Java 22) ignores parts you don't need. Primitive patterns are still in preview in Java 27.
The idea
Object-oriented design puts behavior inside the objects: a Shape knows its own area(). That's the right choice when the set of operations is stable and new types keep arriving. But many programs face the opposite: the types are a fixed set (payment methods, JSON nodes, commands, events) and the operations keep growing. Java 7 handled that with the visitor pattern, which needed an interface, an accept method in every class and a visitor class for each operation.
Data-oriented programming models the fixed set directly:
flowchart LR
P["sealed interface Payment"] --> C["record Card(last4, cents)"]
P --> U["record Upi(vpa, cents)"]
P --> CA["record Cash(cents)"]
S["switch (payment)<br/>case Card(…) → …<br/>case Upi(…) → …<br/>case Cash(…) → …"] -. "compiler checks every case" .-> P
Picture it: a counter with three ways to pay
A trail office accepts exactly three ways to pay: card, UPI or cash. Its manual has one page per task (refunds, receipts, daily totals), and every page covers all three. If the office starts accepting a fourth method, every page must be updated. A sealed interface is the list of accepted payments, and an exhaustive switch is the compiler checking that every page covers every one.
Records, in more depth
Chapter 4 introduced records. They can do more than hold fields:
public class RecordRules {
record Range(int low, int high) {
Range { // compact constructor: validate and normalize
if (low > high) {
throw new IllegalArgumentException(low + " > " + high);
}
}
// extra constructors must delegate
Range(int single) { this(single, single); }
// ordinary methods are fine
int length() { return high - low; }
static Range of(int a, int b) {
return new Range(Math.min(a, b), Math.max(a, b));
}
}
public static void main(String[] args) {
Range r = new Range(7, 27);
System.out.println(r + " length " + r.length());
System.out.println(new Range(5));
System.out.println(Range.of(27, 7));
try {
new Range(27, 7);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
- A compact constructor (
Range { … }) runs validation before the fields are assigned; no parameter list, no assignments. - Extra constructors must delegate to the canonical one with
this(...). - Methods and static factories are fine. Instance fields beyond the components aren't.
- Records can implement interfaces, which is how they join a sealed hierarchy.
Sealed types plus record patterns
public class Payments {
sealed interface Payment permits Card, Upi, Cash { }
record Card(String last4, long cents) implements Payment { }
record Upi(String vpa, long cents) implements Payment { }
record Cash(long cents) implements Payment { }
static String receipt(Payment p) {
return switch (p) { // exhaustive: no default
case Card(String last4, long cents) when cents > 100_000 ->
"card *" + last4 + " (needs approval)";
case Card(String last4, long cents) ->
"card *" + last4 + " " + cents;
case Upi(String vpa, long cents) -> "upi " + vpa + " " + cents;
case Cash(long cents) -> "cash " + cents;
};
}
public static void main(String[] args) {
Payment[] payments = {
new Card("4242", 2_500), new Card("1881", 250_000),
new Upi("asha@bank", 900), new Cash(100) };
for (Payment p : payments) System.out.println(receipt(p));
}
}
Picture it: unpacking a parcel
Without patterns, you checked the label on a parcel (instanceof), opened it (a cast), and took each item out by hand (one accessor call per component). A record pattern does all three in one move: "if this is a Card, put its digits here and its amount there.
case Card(String last4, long cents) is a record pattern (JEP 440): it tests the type and extracts the components in one step. Guards (when) refine a case. And because Payment is sealed, the switch needs no default. If you add record Wallet(...) implements Payment, this method stops compiling until you handle it. Compare that with Java 7, where a new subclass silently fell into an else branch.
Ignoring what you don't need: _ (Java 22)
public class UnnamedPatterns {
sealed interface Shape permits Circle, Square, Rect { }
record Circle(double r) implements Shape { }
record Square(double side) implements Shape { }
record Rect(double w, double h) implements Shape { }
static String corners(Shape s) {
return switch (s) {
// Java 22: _ for an unused binding
case Circle _ -> "no corners";
// several patterns, one case
case Square _, Rect _ -> "four corners";
};
}
static boolean isWide(Shape s) {
// ignore the height component
return s instanceof Rect(var w, _) && w > 10;
}
public static void main(String[] args) {
System.out.println(corners(new Circle(1)) + ", "
+ corners(new Rect(2, 3)));
System.out.println(isWide(new Rect(12, 1)) + " "
+ isWide(new Square(20)));
}
}
_ (JEP 456) marks a pattern or component you don't care about. It also lets several patterns share one case (case Square _, Rect _), which isn't allowed when the patterns bind names.
The journey at a glance
timeline
title Data-oriented Java
2011 : Java 7 : classes + visitor pattern, instanceof then cast
2021 : Java 16 : records, pattern matching for instanceof
: Java 17 : sealed classes and interfaces
2023 : Java 21 : record patterns, pattern matching for switch
2024 : Java 22 : unnamed variables and patterns _
2026 : Java 27 : primitive types in patterns (fifth preview)
Migration tip
Good candidates: classes that only carry data (→ records), hierarchies with an if/else instanceof ladder or a visitor (→ sealed interface + switch), and "type code" enums paired with nullable fields (→ one record per case). Keep classic object-oriented polymorphism where new types are added often and operations rarely change.
Go deeper in the complete edition
This page is the focused edition. The complete edition of this chapter on GitHub adds the deep dives, puzzles, exercises and interview questions, with every sample ready to run.
Summary
- Records hold data; sealed interfaces fix the set of alternatives; patterns take data apart.
- Exhaustive
switchover sealed types turns "forgot a case" into a compile error. - Java 22's
_keeps patterns focused; primitive patterns are still previewing in Java 27.
Next: Chapter 20 closes the journey with the tools around the language: the HTTP client, jlink, jpackage, JFR and more.