Programming languages · Intermediate · 22 min
Model data in Java 25 with records, sealed interfaces and pattern matching
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Eclipse Temurin JDK 25.0.5
You will replace a mutable Java class with a validated record, model payments as a sealed interface, price them with a switch the compiler checks for missing cases, and run it all as a multi-file program straight from source on Java 25.
On this page
Most code that handles money, orders or messages spends its time asking two questions: what does this value hold, and which kind of value is it? Older Java answered the first with classes full of getters, setters, equals and hashCode, and the second with instanceof chains or a type field and a default branch that hoped for the best.
Java 25 has better tools for both. A record is a class that holds data and nothing else, with its methods written for you. A sealed interface lists every kind of value that can exist, so the compiler knows when a switch has covered them all. Record patterns take a value apart inside a case, and guards add conditions to it.
In this tutorial you start from a mutable customer class and see what goes wrong, rewrite it as a record, learn where records stop protecting you, then build a small payment model with card, mobile money and bank transfer payments. You price each one with a switch that has no default, split the code into several files, and add a new payment type to watch the compiler point at every place that needs to change. You run everything with java File.java, so there is no build tool to set up.
Amounts are stored as whole numbers of the currency's smallest unit (kobo, cents, pesewas), never as double. The fee rules are made up for the example.
Step 1 · Check your JDK and make a demo folder
Records arrived in Java 16, sealed types in 17 and pattern matching for switch in 21. This tutorial also uses the unnamed _ pattern (Java 22), multi-file source launching (Java 22) and compact source files (final in Java 25), so you need JDK 25 or later. If you do not have it yet, follow Hello World in Java first.
java -version
mkdir -p ~/java-records-demo
cd ~/java-records-demoJDK 25 is the current long-term support release. JDK 27 is newer and everything here works on it too.
Check it worked
java -version prints a first line something like openjdk version "25.0.5", and pwd shows you are in java-records-demo in your home folder.
Step 2 · See what goes wrong with a mutable class
Here is a customer written the traditional way: private fields, a constructor, getters and setters. Create CustomerBean.java:
cat > CustomerBean.java <<'JAVA'
class Customer {
private String id;
private String name;
private String email;
Customer(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
String getName() { return name; }
void setName(String name) { this.name = name; }
String getEmail() { return email; }
void setEmail(String email) { this.email = email; }
}
void main() {
var a = new Customer("c-1", "Amara Obi", "amara@example.com");
var b = new Customer("c-1", "Amara Obi", "amara@example.com");
IO.println("same data, equal? " + a.equals(b));
IO.println("printed: " + a);
a.setEmail("");
IO.println("email after setEmail(\"\"): '" + a.getEmail() + "'");
}
JAVA
java CustomerBean.javaThis is a compact source file: void main() and the Customer class sit at the top level, and the launcher wraps them in a class named after the file. java CustomerBean.java compiles it in memory and runs it, leaving no .class file behind.
Three problems show up in a few lines:
- Two customers with the same data are not equal, because
equalsfalls back to comparing object identity. Put them in aHashSetand you get two entries. - Printing one gives a class name and a hash code, not the data, which is useless in a log.
- Any code holding a reference can set the email to an empty string, and nothing stops it.
You could fix all three by hand, with equals, hashCode, toString and checks in every setter, but that is roughly 40 lines to write, review and keep in step each time a field is added.
Check it worked
The program prints same data, equal? false, then printed: followed by something like CustomerBean$Customer@5ca881b5, then email after setEmail(""): ''.
Step 3 · Rewrite it as a record with validation
A record declares its fields in a header. Java generates a private final field, a public accessor method and a constructor for each one, plus equals, hashCode and toString based on all of them. Create CustomerRecord.java:
cat > CustomerRecord.java <<'JAVA'
record Customer(String id, String name, String email) {
Customer {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(email, "email");
name = name.strip();
if (name.isEmpty()) {
throw new IllegalArgumentException("name must not be blank");
}
if (!email.contains("@")) {
throw new IllegalArgumentException("email needs an @: " + email);
}
}
Customer withEmail(String newEmail) {
return new Customer(id, name, newEmail);
}
}
void main() {
var a = new Customer("c-1", " Amara Obi ", "amara@example.com");
var b = new Customer("c-1", "Amara Obi", "amara@example.com");
IO.println("equal? " + a.equals(b));
IO.println("same hash? " + (a.hashCode() == b.hashCode()));
IO.println(a);
IO.println("name accessor: " + a.name());
var moved = a.withEmail("amara.obi@example.org");
IO.println(moved);
IO.println("original unchanged: " + a.email());
try {
new Customer("c-2", "Kofi Mensah", "not-an-email");
} catch (IllegalArgumentException e) {
IO.println("rejected: " + e.getMessage());
}
}
JAVA
java CustomerRecord.javaWhat each part does:
record Customer(String id, String name, String email)is the whole data definition. The fields are final, so there are no setters.Customer { ... }with no parameter list is a compact constructor. It runs before the fields are assigned, with the parameters already in scope. You can check them, throw, or replace a parameter (name = name.strip()), and Java assigns the fields afterwards. Every record created anywhere goes through it, so an invalid customer cannot exist.- The accessors are named after the components:
a.name(), nota.getName(). withEmailis an ordinary method. To "change" a record you build a new one, and the old one stays as it was. Because the new one goes through the compact constructor too, it is validated.Objectsand the otherjava.utilclasses need no import in a compact source file, because it imports the wholejava.basemodule for you. In a normal class file you writeimport java.util.Objects;.
The two customers are equal even though one name had extra spaces, because the compact constructor stripped them before the fields were set.
Check it worked
The output starts equal? true and same hash? true, prints Customer[id=c-1, name=Amara Obi, email=amara@example.com] with no spaces around the name, and ends with rejected: email needs an @: not-an-email.
Step 4 · Learn what records cannot do
Records save a lot of code, but they have firm limits. The one that bites most often is that their immutability is shallow: a final field that points at a mutable list still lets the list change. Create Shallow.java:
cat > Shallow.java <<'JAVA'
record Basket(String owner, List<String> items) {}
record SafeBasket(String owner, List<String> items) {
SafeBasket {
items = List.copyOf(items);
}
}
void main() {
var shopping = new ArrayList<String>(List.of("rice", "beans"));
var basket = new Basket("Amara", shopping);
var safe = new SafeBasket("Amara", shopping);
shopping.add("plantain");
IO.println("Basket: " + basket.items());
IO.println("SafeBasket: " + safe.items());
try {
safe.items().add("yam");
} catch (UnsupportedOperationException e) {
IO.println("SafeBasket items cannot be changed");
}
}
JAVA
java Shallow.javaBasket stores the caller's own list, so when the caller adds plantain, the "immutable" basket changes too. SafeBasket copies the list in its compact constructor with List.copyOf, which returns an unmodifiable copy, so later changes to shopping do not reach it and add on its items throws. List.copyOf also rejects null elements with a NullPointerException, which is usually what you want in a data model. Do the same for maps (Map.copyOf), sets (Set.copyOf) and arrays (.clone()).
The second limit is inheritance. A record is final and cannot extend another class. Try to build on one:
cat > Extend.java <<'JAVA'
record Point(int x, int y) {}
class Point3D extends Point {
int z;
}
void main() {}
JAVA
java Extend.java || trueThe launcher stops with a compile error, and || true only keeps that expected failure from ending a script you paste this into. The full list of what a record cannot do:
- It cannot extend a class (it already extends
java.lang.Record), and no class can extend it. It can implement interfaces, which is what the next step relies on. - It cannot declare instance fields beyond its components. Static fields and any methods you like are fine.
- Its fields are final, so there are no setters. Anything that needs to change in place, such as an object a framework fills in field by field, is not a record.
- It cannot hide its components: every one gets a public accessor and appears in
toString. Do not put a password or card number in a record you might log.
Check it worked
Shallow.java prints Basket: [rice, beans, plantain], SafeBasket: [rice, beans] and SafeBasket items cannot be changed. java Extend.java prints an error containing cannot inherit from final.
Step 5 · Model payments with a sealed interface
A shop takes three kinds of payment. A card payment has the last four digits and whether the card is foreign. A mobile money payment has a phone number. A bank transfer has an account number. Each has an amount. A sealed interface says exactly which types may implement it, and each type can be a record with only the fields it needs. Create Payments.java:
cat > Payments.java <<'JAVA'
record Money(long minor, String currency) {
Money {
if (minor < 0) {
throw new IllegalArgumentException("amount must not be negative");
}
if (currency == null || !currency.matches("[A-Z]{3}")) {
throw new IllegalArgumentException("currency must be a code such as NGN");
}
}
@Override
public String toString() {
return "%s %d.%02d".formatted(currency, minor / 100, minor % 100);
}
}
sealed interface Payment permits Card, MobileMoney, BankTransfer {
Money amount();
}
record Card(String last4, Money amount, boolean international) implements Payment {}
record MobileMoney(String phone, Money amount) implements Payment {}
record BankTransfer(String accountNumber, Money amount) implements Payment {}
String describe(Payment p) {
return switch (p) {
case Card c -> "card ending " + c.last4() + ", " + c.amount();
case MobileMoney m -> "mobile money from " + m.phone() + ", " + m.amount();
case BankTransfer b -> "bank transfer from " + b.accountNumber() + ", " + b.amount();
};
}
void main() {
List<Payment> payments = List.of(
new Card("4242", new Money(250_000, "NGN"), false),
new MobileMoney("+254700000001", new Money(80_000, "KES")),
new BankTransfer("0123456789", new Money(1_000_000, "GHS")));
for (Payment p : payments) {
IO.println(describe(p));
}
}
JAVA
java Payments.javaThe pieces:
Moneyis a small record that refuses negative amounts and anything that is not a three-letter code. It overridestoStringto printNGN 2500.00instead ofMoney[minor=250000, currency=NGN]. 250,000 kobo is 2,500 naira, andlongarithmetic never rounds the waydoubledoes.sealed interface Payment permits Card, MobileMoney, BankTransfermeans those three are the only implementations. A fourth class that tries to implementPaymentis a compile error.Money amount()in the interface is satisfied by each record'samountcomponent, because the generated accessor has exactly that signature.- The
switchindescribeuses type patterns:case Card cchecks the type and gives you a variablecof typeCard, with no cast. There is nodefault. The compiler accepts that because it knows frompermitsthat these three cases cover everyPayment.
One thing the sealed switch does not handle for you: if p is null, it throws a NullPointerException. Add case null -> if null can really reach it.
Mobile money is how many people in East and West Africa pay, often from a low-end Android phone. Giving it its own type, rather than squeezing a phone number into a card field, keeps each payment honest about what it carries.
Check it worked
The program prints three lines: card ending 4242, NGN 2500.00, mobile money from +254700000001, KES 800.00 and bank transfer from 0123456789, GHS 10000.00.
Step 6 · Split the model into files and launch it from source
One file is fine for an experiment. A real model has a file per type. Since Java 22 the java launcher can run a program spread over several source files: you launch the file with main, and it finds and compiles the other classes it needs from the same folder. Make a fresh folder so the earlier files do not get in the way:
mkdir -p ~/java-records-demo/shop
cd ~/java-records-demo/shop
cat > Money.java <<'JAVA'
record Money(long minor, String currency) {
Money {
if (minor < 0) {
throw new IllegalArgumentException("amount must not be negative");
}
if (currency == null || !currency.matches("[A-Z]{3}")) {
throw new IllegalArgumentException("currency must be a code such as NGN");
}
}
@Override
public String toString() {
return "%s %d.%02d".formatted(currency, minor / 100, minor % 100);
}
}
JAVA
cat > Payment.java <<'JAVA'
sealed interface Payment permits Card, MobileMoney, BankTransfer {
Money amount();
}
JAVA
cat > Card.java <<'JAVA'
record Card(String last4, Money amount, boolean international) implements Payment {}
JAVA
cat > MobileMoney.java <<'JAVA'
record MobileMoney(String phone, Money amount) implements Payment {}
JAVA
cat > BankTransfer.java <<'JAVA'
record BankTransfer(String accountNumber, Money amount) implements Payment {}
JAVA
cat > Checkout.java <<'JAVA'
final class Checkout {
private Checkout() {}
static String describe(Payment p) {
return switch (p) {
case Card c -> "card ending " + c.last4() + ", " + c.amount();
case MobileMoney m -> "mobile money from " + m.phone() + ", " + m.amount();
case BankTransfer b -> "bank transfer from " + b.accountNumber() + ", " + b.amount();
};
}
}
JAVA
cat > Main.java <<'JAVA'
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Payment> payments = List.of(
new Card("4242", new Money(250_000, "NGN"), false),
new MobileMoney("+254700000001", new Money(80_000, "KES")),
new BankTransfer("0123456789", new Money(1_000_000, "GHS")));
for (Payment p : payments) {
IO.println(Checkout.describe(p));
}
}
}
JAVA
java Main.java
lsjava Main.java compiles Main.java in memory, sees that it uses Payment, Card, Money and Checkout, and compiles each from the file of the same name in this folder. The permits clause pulls in all three payment records. Nothing is written to disk.
Main is an ordinary class with the classic public static void main. A compact file would work as the entry point too, but its class has no name other files can use, so a named class is the better habit once a program has several files. The other files are normal top-level types: one type per file, the file named after the type.
When the program outgrows this, compile it with javac or a build tool such as Maven or Gradle. The source files do not change.
Check it worked
java Main.java prints the same three lines as the previous step. ls lists seven .java files and no .class files.
Step 7 · Price payments with record patterns and guards
Now add fees. The made-up rules: cards pay 1.5%, or 2.5% when the card is foreign; mobile money pays a flat 50 minor units up to 1,000.00 and 1% above that; bank transfers pay a flat 100. Replace Checkout.java and Main.java:
cat > Checkout.java <<'JAVA'
final class Checkout {
private Checkout() {}
static String describe(Payment p) {
return switch (p) {
case Card c -> "card ending " + c.last4() + ", " + c.amount();
case MobileMoney m -> "mobile money from " + m.phone() + ", " + m.amount();
case BankTransfer b -> "bank transfer from " + b.accountNumber() + ", " + b.amount();
};
}
static long fee(Payment p) {
return switch (p) {
case Card(_, Money(long minor, _), boolean foreign) when foreign -> minor * 250 / 10_000;
case Card(_, Money(long minor, _), _) -> minor * 150 / 10_000;
case MobileMoney(_, Money(long minor, _)) when minor <= 100_000 -> 50;
case MobileMoney(_, Money(long minor, _)) -> minor / 100;
case BankTransfer _ -> 100;
};
}
}
JAVA
cat > Main.java <<'JAVA'
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Payment> payments = List.of(
new Card("4242", new Money(250_000, "NGN"), false),
new Card("1881", new Money(250_000, "NGN"), true),
new MobileMoney("+254700000001", new Money(80_000, "KES")),
new MobileMoney("+254700000002", new Money(500_000, "KES")),
new BankTransfer("0123456789", new Money(1_000_000, "GHS")));
for (Payment p : payments) {
Money fee = new Money(Checkout.fee(p), p.amount().currency());
IO.println(Checkout.describe(p) + ", fee " + fee);
}
}
}
JAVA
java Main.javaRead the fee switch case by case:
case Card(_, Money(long minor, _), boolean foreign)is a record pattern. It matches aCard, takes it apart into its three components and, because the second component is itself a record, takes that apart too. You getminorandforeignas variables in one line._means "a component I do not need", so you do not invent names forlast4orcurrency.when foreignis a guard. The case matches only if the pattern fits and the condition is true. A foreign card falls into the first case; any other card falls through to the second, which has no guard.- The two mobile money cases work the same way, with a guard on the amount.
case BankTransfer _matches the type and binds nothing, because the fee does not depend on any field.
Order matters. Java tries cases top to bottom, and a guarded case must come before the unguarded one for the same type. If you swap the two Card lines, the compiler reports that the guarded case is dominated by the one above it and can never run. The switch still needs no default: the unguarded Card and MobileMoney cases, plus BankTransfer, cover every Payment.
The fee is calculated in minor units with whole-number division, which rounds down. 1.5% of NGN 2,500.00 is NGN 37.50 exactly; for amounts that do not divide evenly, decide your rounding rule with whoever owns the money.
Check it worked
Five lines print, ending fee NGN 37.50, fee NGN 62.50, fee KES 0.50, fee KES 50.00 and fee GHS 1.00.
Step 8 · Add a payment type and let the compiler find the gaps
The shop now accepts gift vouchers. In code with a type field and default branches, a new type slips through every switch silently and gets whatever the default does. With a sealed interface, the compiler finds every place you need to update. Add the record and list it in permits:
cat > Voucher.java <<'JAVA'
record Voucher(String code, Money amount) implements Payment {}
JAVA
cat > Payment.java <<'JAVA'
sealed interface Payment permits Card, MobileMoney, BankTransfer, Voucher {
Money amount();
}
JAVA
java Main.java || trueThe launcher refuses to run. It reports two errors in Checkout.java, one for describe and one for fee, each saying the switch expression does not cover all possible input values. Nothing ran, so no payment was described or priced wrongly. Handle vouchers in both, with no fee, and add one to the list:
cat > Checkout.java <<'JAVA'
final class Checkout {
private Checkout() {}
static String describe(Payment p) {
return switch (p) {
case Card c -> "card ending " + c.last4() + ", " + c.amount();
case MobileMoney m -> "mobile money from " + m.phone() + ", " + m.amount();
case BankTransfer b -> "bank transfer from " + b.accountNumber() + ", " + b.amount();
case Voucher v -> "voucher " + v.code() + ", " + v.amount();
};
}
static long fee(Payment p) {
return switch (p) {
case Card(_, Money(long minor, _), boolean foreign) when foreign -> minor * 250 / 10_000;
case Card(_, Money(long minor, _), _) -> minor * 150 / 10_000;
case MobileMoney(_, Money(long minor, _)) when minor <= 100_000 -> 50;
case MobileMoney(_, Money(long minor, _)) -> minor / 100;
case BankTransfer _ -> 100;
case Voucher _ -> 0;
};
}
}
JAVA
cat > Main.java <<'JAVA'
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Payment> payments = List.of(
new Card("4242", new Money(250_000, "NGN"), false),
new Card("1881", new Money(250_000, "NGN"), true),
new MobileMoney("+254700000001", new Money(80_000, "KES")),
new MobileMoney("+254700000002", new Money(500_000, "KES")),
new BankTransfer("0123456789", new Money(1_000_000, "GHS")),
new Voucher("WELCOME10", new Money(100_000, "NGN")));
for (Payment p : payments) {
Money fee = new Money(Checkout.fee(p), p.amount().currency());
IO.println(Checkout.describe(p) + ", fee " + fee);
}
}
}
JAVA
java Main.javaThis is the payoff of the whole model. The list of payment types lives in one line, permits, and every switch without a default is checked against it. If you had written default -> 0 in fee, the compiler would have stayed quiet and vouchers would have been priced by accident. Keep default out of switches over sealed types unless you really mean "everything else, including types added later".
When you have finished, leave the folder and remove only what this tutorial created:
cd ~
rm -rf ~/java-records-demoCheck it worked
The first java Main.java fails with two does not cover all possible input values errors. After the fix it prints six lines, the last being voucher WELCOME10, NGN 1000.00, fee NGN 0.00. After the clean-up, ls ~/java-records-demo reports that there is no such file or directory.
Next steps
- Process lists of these payments, totalling fees per currency, in Transform collections with Java streams and collectors.
- Turn the
shopfolder into a tested project with Build and test a Java project with Maven. - Compare the same payment model in TypeScript in Narrow types safely with TypeScript discriminated unions.
- See how Python handles the record side of this in Model data with Python dataclasses.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials