AdvancedLesson 13 of 16
sealed, Pattern Matching & Record Patterns – Java
Closed type hierarchies and expressive case distinctions checked by the compiler.
With sealed (Java 17) you define which classes may implement an interface. Combined with records and pattern-matching switch (Java 21), this yields an algebraic data type: the compiler checks that all cases are handled.
sealed interface Form permits Kreis, Rechteck, Dreieck {}
record Kreis(double radius) implements Form {}
record Rechteck(double breite, double hoehe) implements Form {}
record Dreieck(double grundseite, double hoehe) implements Form {}
static double flaeche(Form f) {
return switch (f) {
case Kreis k -> Math.PI * k.radius() * k.radius();
case Rechteck r -> r.breite() * r.hoehe();
case Dreieck d -> d.grundseite() * d.hoehe() / 2;
}; // no default: if you add a new shape, the compiler reports the missing case
}Record patterns destructure records directly in the pattern, even when nested. With when you attach a condition (guard):
sealed interface Ausdruck permits Zahl, Add, Mul {}
record Zahl(int wert) implements Ausdruck {}
record Add(Ausdruck links, Ausdruck rechts) implements Ausdruck {}
record Mul(Ausdruck links, Ausdruck rechts) implements Ausdruck {}
static int auswerten(Ausdruck e) {
return switch (e) {
case Zahl z -> z.wert();
case Add(Ausdruck l, Ausdruck r) -> auswerten(l) + auswerten(r);
case Mul(Ausdruck l, Ausdruck r) -> auswerten(l) * auswerten(r);
};
}
// 2 + 3 * 4
System.out.println(auswerten(new Add(new Zahl(2), new Mul(new Zahl(3), new Zahl(4))))); // 14Pattern matching also works for arbitrary objects – with instanceof and with switch. In Java 21 you can handle null as a case of its own.
static String beschreibe(Object o) {
return switch (o) {
case null -> "nothing";
case Integer i when i > 100 -> "large number " + i;
case Integer i -> "Number " + i;
case String s -> "Text with " + s.length() + " characters";
case int[] arr -> "int array of length " + arr.length;
default -> "unknown: " + o.getClass().getSimpleName();
};
}
Object x = "Hello";
if (x instanceof String s && s.length() > 3) {
System.out.println(s.toUpperCase()); // HELLO
}
System.out.println(beschreibe(500)); // large number 500
System.out.println(beschreibe(null)); // nothingWarningIn a pattern
switch the order matters: a more general pattern before a more specific one makes the latter unreachable – the compiler reports this as an error. So the guarded case (Integer i when ...) must come before Integer i.TipSealed hierarchies plus
switch often replace the visitor pattern. Rather than a default branch, list all cases – that way, when you extend the hierarchy, you find every place that has to be adapted.