Because the compiler knows every permitted subtype, a switch over a sealed hierarchy needs no default branch - and adding a subtype turns missed cases into compile errors.
sealed interface Event permits Login, Purchase, Logout {}
record Login(String user) implements Event {}
record Purchase(String user, int amount) implements Event {}
record Logout(String user) implements Event {}
List<Event> events = List.of(new Login("ava"), new Purchase("ava", 99), new Logout("ava"));
for (Event e : events) {
String line = switch (e) { // no default needed
case Login l -> l.user() + " signed in";
case Purchase p -> p.user() + " spent " + p.amount();
case Logout l -> l.user() + " signed out";
};
System.out.println(line);
}
ava signed in
ava spent 99
ava signed out
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30