JAVA-230 · Lesson 11 of 12 · 22 min
Sealed classes and modern language features
▶ Video coming soon A video version of this lesson is on the way.
The last regular session, on Wednesday, December 1, picked up where the previous one stopped. Hamza's switch over shop events still needed a default case, because its parameter was Object and the compiler could not know every kind of event. "But we know," he said. "There are exactly four: rentals, repairs, sales and fittings." Ingrid wrote sealed on the whiteboard. A sealed class or interface, final in Java 17, lists the only classes allowed to extend or implement it. That closed list lets the compiler check a switch for completeness, and lets the code say in its types that the set of possibilities is fixed. The rest of the evening was a tour of the other modern features Hamza would meet in current Java code, including several that arrived after Java 21.
Sealed types
A sealed type names its permitted subtypes with a permits clause. Each permitted subtype must say how the line continues: final (no further subclasses), sealed (its own closed list) or non-sealed (open again for anyone to extend). Records are implicitly final, so they fit naturally. If the permitted subtypes are in the same file, the permits clause can be left out and the compiler finds them. Permitted subtypes must be in the same package as the sealed type, or in the same module if the code uses modules.
import java.util.*;
public class Main {
sealed interface ShopEvent permits Rental, Repair, Sale, Fitting { }
record Rental(String bike, int days) implements ShopEvent { }
record Repair(int ticket, int minutes) implements ShopEvent { }
record Sale(String code, long cents) implements ShopEvent { }
record Fitting(String part, int count) implements ShopEvent { }
static int shopMinutes(ShopEvent e) {
return switch (e) {
case Rental r -> 10; // check-out and check-in
case Repair(int ticket, int minutes) -> minutes;
case Sale s -> 0;
case Fitting(String part, int count) -> count * 10;
};
}
public static void main(String[] args) {
List<ShopEvent> day = List.of(new Rental("CITY-2", 2), new Repair(531, 45),
new Sale("TUBE-700x25", 899), new Fitting("BELL", 2), new Repair(532, 30));
int total = 0;
for (ShopEvent e : day) total += shopMinutes(e);
System.out.println("Shop time for the day: " + total + " minutes");
System.out.println("ShopEvent is sealed: " + ShopEvent.class.isSealed());
System.out.println("Permitted: " + Arrays.stream(ShopEvent.class.getPermittedSubclasses())
.map(Class::getSimpleName).toList());
}
}Shop time for the day: 105 minutes ShopEvent is sealed: true Permitted: [Rental, Repair, Sale, Fitting]
What this code does
Because ShopEvent permits exactly four records, the switch in shopMinutes covers every case without a default, and the compiler has checked that. The day's events add up to 10 + 45 + 0 + 20 + 30 = 105 minutes of shop time. Reflection confirms at run time that the interface is sealed and lists the four permitted classes.
The value of leaving out default shows up when the list changes. If Odile later wants a fifth event, say a donation, adding Donation to the permits clause makes every exhaustive switch over ShopEvent fail to compile until it handles donations. With a default case, those switches would quietly put donations into the default branch, which is exactly the kind of bug that slips through review.
public class Main {
sealed interface ShopEvent permits Rental, Repair, Donation { }
record Rental(String bike, int days) implements ShopEvent { }
record Repair(int ticket, int minutes) implements ShopEvent { }
record Donation(String donor, int bikes) implements ShopEvent { }
static int shopMinutes(ShopEvent e) {
return switch (e) {
case Rental r -> 10;
case Repair(int ticket, int minutes) -> minutes;
};
}
public static void main(String[] args) {
System.out.println(shopMinutes(new Repair(531, 45)));
}
}What this code does
Donation was added to the permits clause, but shopMinutes still handles only rentals and repairs. The compiler reports that the switch expression does not cover all possible input values, which points at the one method that needs a new case. That is the safety a sealed hierarchy buys: forgetting a case becomes a compile error, not a wrong number in a report.
$ javac Main.java
Main.java:8: error: the switch expression does not cover all possible input values
return switch (e) {
^
1 errorRecords, sealed types and data-oriented programming
Together, records and sealed types let you model data as a closed set of shapes, each with exactly the fields it needs, and write operations as switches over those shapes. This style, called data-oriented programming, suits the reporting code in this course well: the data is plain and immutable, the operations live in one place, and adding an operation means writing one new method with a switch rather than adding a method to every class. The classic object-oriented style, a method on each class, is better when the set of operations is fixed and the set of types grows; data-oriented style is better when the set of types is fixed and the operations grow, which is what a report generator looks like.
import java.util.*;
import java.util.stream.*;
public class Main {
sealed interface Charge permits PartCharge, LabourCharge, Discount { }
record PartCharge(String code, int quantity, long unitCents) implements Charge { }
record LabourCharge(int minutes, long centsPerHour) implements Charge { }
record Discount(String reason, long cents) implements Charge { }
static long amount(Charge c) {
return switch (c) {
case PartCharge(var code, var qty, var unit) -> qty * unit;
case LabourCharge(var minutes, var rate) -> Math.round(minutes * rate / 60.0);
case Discount(var reason, var cents) -> -cents;
};
}
static String describe(Charge c) {
return switch (c) {
case PartCharge p -> p.quantity() + " x " + p.code();
case LabourCharge l -> l.minutes() + " min shop time";
case Discount d -> "discount: " + d.reason();
};
}
public static void main(String[] args) {
List<Charge> bill = List.of(new PartCharge("CABLE-BRAKE", 2, 799),
new LabourCharge(45, 4000), new Discount("volunteer", 500));
for (Charge c : bill) System.out.printf("%-28s %7.2f%n", describe(c), amount(c) / 100.0);
System.out.printf("%-28s %7.2f%n", "Total before tax", bill.stream().mapToLong(Main::amount).sum() / 100.0);
}
}2 x CABLE-BRAKE 15.98 45 min shop time 30.00 discount: volunteer -5.00 Total before tax 40.98
What this code does
Each kind of charge is a record with only the fields it needs, and amount and describe are separate switches over the sealed Charge type, so a new report column is one new method rather than a change to three classes. Forty-five minutes at the shop's rate of 40 dollars an hour comes to 3,000 cents. The volunteer discount is a negative amount, so the total before tax is 1,598 + 3,000 - 500 = 4,098 cents.
Other features worth knowing in Java 21
Several smaller features from Java 10 to 21 appear throughout modern code. var (Java 10) lets the compiler infer a local variable's type from its initializer, which shortens lines such as var byKind = new EnumMap<Kind, Long>(Kind.class); use it when the type is obvious from the right-hand side and keep explicit types when it is not. Sequenced collections (Java 21), which JAVA-201 introduced, add getFirst, getLast, addFirst, removeLast and reversed to lists, deques, sorted sets and linked maps. Helpful NullPointerException messages (Java 14) name what was null, as lesson 5 showed. And records (Java 16) can have compact constructors, static factory methods and their own methods, as every lesson in this course has used.
import java.util.*;
public class Main {
record Price(String code, long cents) {
static Price of(String code, double dollars) { return new Price(code, Math.round(dollars * 100)); }
String label() { return code + " " + cents / 100 + "." + String.format("%02d", cents % 100); }
}
public static void main(String[] args) {
var prices = new ArrayList<Price>();
prices.add(Price.of("TUBE-700x25", 8.99));
prices.add(Price.of("BELL", 6.50));
prices.add(Price.of("CHAIN-11", 24.99));
System.out.println("First: " + prices.getFirst().label() + ", last: " + prices.getLast().label());
System.out.println("Reversed: " + prices.reversed().stream().map(Price::code).toList());
var newest = new LinkedHashMap<String, Long>();
for (var p : prices) newest.put(p.code(), p.cents());
System.out.println("First entry: " + newest.firstEntry() + ", last entry: " + newest.lastEntry());
newest.putFirst("SADDLE", 3999L);
System.out.println("After putFirst: " + newest.sequencedKeySet());
}
}First: TUBE-700x25 8.99, last: CHAIN-11 24.99 Reversed: [CHAIN-11, BELL, TUBE-700x25] First entry: TUBE-700x25=899, last entry: CHAIN-11=2499 After putFirst: [SADDLE, TUBE-700x25, BELL, CHAIN-11]
What this code does
var infers ArrayList<Price> and LinkedHashMap<String, Long> from the right-hand sides, so the types are still checked but not repeated. getFirst, getLast and reversed come from the SequencedCollection interface added in Java 21, and firstEntry, lastEntry and putFirst from SequencedMap. The record has a static factory method and an instance method of its own alongside its generated accessors.
After Java 21: features Hamza will meet
Java releases twice a year, in March and September, and every release adds something. Java 25, released in September 2025, is the current long-term support release and the one Hamza runs at home; Java 27 arrived in September 2026. This course's runnable examples target Java 21 so that they compile on the widest range of machines, so the newer features below are shown as listings that are not compiled here. Each was final, meaning no longer a preview, in the release named.
| Feature | Final in | What it does |
|---|---|---|
| Unnamed variables and patterns | Java 22 | write _ for a variable or pattern you do not use |
| Markdown documentation comments | Java 23 | write Javadoc in Markdown with /// comments |
| Stream gatherers | Java 24 | custom intermediate operations with Stream.gather |
| Compact source files and instance main methods | Java 25 | void main() with no class declaration for small programs |
| Module import declarations | Java 25 | import module java.base; imports every package of a module |
| Flexible constructor bodies | Java 25 | statements before super(...) or this(...) in a constructor |
// Java 22 and later: unnamed variables and patterns
static int shopMinutes(ShopEvent e) {
return switch (e) {
case Rental _ -> 10;
case Repair(int _, int minutes) -> minutes;
case Sale _ -> 0;
case Fitting(String _, int count) -> count * 10;
};
}
int failures = 0;
for (String line : lines) {
try {
Integer.parseInt(line);
} catch (NumberFormatException _) { // the exception object is not needed
failures++;
}
}What this code does
The underscore marks a variable or pattern component that the code deliberately ignores, such as the ticket number when only the minutes matter. It documents the intent and stops tools warning about an unused variable. This listing needs Java 22 or later, so it is not compiled here.
// Java 24 and later: stream gatherers
import java.util.stream.Gatherers;
List<Integer> dailyRepairs = List.of(6, 9, 4, 11, 7, 3, 8);
// sliding three-day windows
List<List<Integer>> windows = dailyRepairs.stream()
.gather(Gatherers.windowSliding(3))
.toList();
// [[6, 9, 4], [9, 4, 11], [4, 11, 7], [11, 7, 3], [7, 3, 8]]
// running total
List<Integer> runningTotal = dailyRepairs.stream()
.gather(Gatherers.scan(() -> 0, Integer::sum))
.toList();
// [6, 15, 19, 30, 37, 40, 48]What this code does
Gatherers are to intermediate operations what collectors are to terminal ones: a way to define new steps such as sliding windows, fixed-size batches or running totals. Gatherers.windowSliding(3) groups each run of three days, and Gatherers.scan keeps a running total. The results in the comments were worked out by hand, because this listing needs Java 24 and is not compiled here.
// Java 25 and later: a compact source file, saved as Hello.java and run with: java Hello.java
void main() {
IO.println("Second Gear Cycles: " + countOpenRentals() + " bikes out");
}
int countOpenRentals() {
return 3;
}What this code does
A compact source file has no class declaration, and its main method needs no static modifier, no public and no parameter. IO.println is a new convenience class for console output that arrived with this feature. It is meant for learning and for small scripts, while larger programs keep ordinary classes; this listing needs Java 25 and is not compiled here.
Preview features, which must be switched on with --enable-preview, arrive in most releases too, such as primitive types in patterns, which was still in preview through Java 25. They can change before becoming final, so keep them out of production code. A good habit is to read the release notes, or the list of JEPs (JDK Enhancement Proposals), each March and September.
import java.util.*;
public class Main {
sealed interface Shape permits Wheel, Frame { }
record Wheel(int diameterMm) implements Shape { }
record Frame(String material, int sizeCm) implements Shape { }
static String check(Shape s) {
return switch (s) {
case Wheel(int d) when d == 622 -> "700c road wheel";
case Wheel(int d) when d == 559 -> "26-inch mountain wheel";
case Wheel w -> "other wheel, " + w.diameterMm() + " mm";
case Frame(String m, int size) when size >= 56 -> "large " + m + " frame";
case Frame f -> f.material() + " frame, " + f.sizeCm() + " cm";
};
}
public static void main(String[] args) {
List<Shape> donated = List.of(new Wheel(622), new Wheel(559), new Wheel(406),
new Frame("steel", 58), new Frame("aluminum", 52));
donated.forEach(s -> System.out.println(check(s)));
}
}700c road wheel 26-inch mountain wheel other wheel, 406 mm large steel frame aluminum frame, 52 cm
What this code does
The donated parts form a sealed hierarchy of two records, and one switch sorts them using guards on the record components. 622 and 559 millimeters are the standard bead-seat diameters of 700c and 26-inch wheels, so those get names while any other size falls to the general Wheel case. No default is needed, because the guarded and unguarded cases together cover both permitted records.
Hamza's booking events became a sealed ShopEvent interface that night, and the default case disappeared from every switch over it. The capstone next week would lean on everything since September: streams, collectors, Optional, java.time, files, CSV, JSON, text blocks and sealed types.
Try it yourself
Seal the payment types
Make Payment a sealed interface that permits Cash, Card and GiftCard, then complete fee with a switch that has **no default**: cash has no fee, a card costs 2 cents for every 100 cents (use cents * 2 / 100) and a gift card has no fee.
The program should print Fees: 29 cents.
import java.util.*;
public class Main {
interface Payment { }
record Cash(long cents) implements Payment { }
record Card(long cents) implements Payment { }
record GiftCard(String number, long cents) implements Payment { }
static long fee(Payment p) {
return 0;
}
public static void main(String[] args) {
List<Payment> today = List.of(new Cash(2000), new Card(899), new Card(649), new GiftCard("G-17", 2500));
long total = 0;
for (Payment p : today) total += fee(p);
System.out.println("Fees: " + total + " cents");
}
}Try it yourself
First and last with sequenced collections
Use getFirst, getLast and reversed (from Java 21's sequenced collections) to print the first and last repair ticket in the list and then the whole list in reverse order.
The program should print First: 531, Last: 536 and Reversed: [536, 535, 534, 533, 532, 531].
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> tickets = List.of(531, 532, 533, 534, 535, 536);
System.out.println("First: " + tickets.get(1));
System.out.println("Last: " + tickets.get(tickets.size() - 2));
System.out.println("Reversed: " + tickets);
}
}Common mistakes
MistakeAdding a default case to a switch over a sealed type.
InsteadLeave it out so the compiler reports any new permitted subtype that is not handled.
MistakeForgetting to mark permitted subclasses final, sealed or non-sealed.
InsteadChoose one for each; records are implicitly final.
MistakeUsing var where the type is not obvious.
InsteadKeep explicit types when the right-hand side does not make the type clear.
MistakeUsing preview features in production code.
InsteadWait until a feature is final; previews can change.
MistakeAssuming the newest syntax compiles everywhere.
InsteadCheck the Java version your team and build target, and use newer features only when it allows them.
Summary and key terms
- A sealed class or interface, final in Java 17, lists its permitted subtypes with permits, and each must be final, sealed or non-sealed; records are implicitly final.
- A switch over a sealed type can be exhaustive without a default, so adding a permitted subtype makes every incomplete switch fail to compile.
- Records plus sealed types support data-oriented programming: a closed set of plain data shapes and operations written as switches.
- Other features in Java 21 include var for local variables, sequenced collections with getFirst, getLast and reversed, helpful NullPointerException messages and records with factory methods and compact constructors.
- After Java 21 came unnamed variables and patterns (Java 22), Markdown documentation comments (Java 23), stream gatherers (Java 24), and compact source files, module import declarations and flexible constructor bodies (Java 25, the current long-term support release).
- Preview features need --enable-preview and can change.
- Sealed class or interface
- A type that lists exactly which classes may extend or implement it.
- permits
- The clause that names a sealed type's permitted subtypes.
- non-sealed
- A modifier that reopens a permitted subtype so anyone may extend it.
- Data-oriented programming
- Modeling data as closed sets of immutable records and writing operations as switches over them.
- var
- A keyword that lets the compiler infer a local variable's type from its initializer.
- Sequenced collection
- A Java 21 collection type with a defined order and methods such as getFirst and reversed.
- Unnamed variable
- A variable written _ because the code does not use it (Java 22).
- Stream gatherer
- A custom intermediate stream operation used with Stream.gather (Java 24).
- Preview feature
- A language or library feature available for testing that may change before it is final.
- JEP
- JDK Enhancement Proposal, the document that describes a new Java feature.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What does sealed interface ShopEvent permits Rental, Repair mean?
Show answer
Only Rental and Repair may implement ShopEvent.
Why can a switch over a sealed type leave out default?
Show answer
The compiler knows every permitted subtype and checks that each is handled.
What happens to an exhaustive switch when a new permitted subtype is added?
Show answer
It fails to compile until the new subtype is handled.
Which Java 21 methods give the first and last element of a list?
Show answer
getFirst and getLast.
In which release did stream gatherers become final?
Show answer
Java 24.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.