With sealed types the compiler knows all cases, so no default is needed.
sealed interface Msg permits Text, Ping {}
record Text(String body) implements Msg {}
record Ping() implements Msg {}
Msg m = new Text("hi");
String out = switch (m) {
case Text t -> "text: " + t.body();
case Ping p -> "ping";
};
System.out.println(out);
text: hi
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-26