Java

Sealed Classes + Pattern Matching (Java 21+)

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`sealed` restricts which classes can extend a type — perfect for closed hierarchies that pattern matching can switch over exhaustively. The compiler enforces that you handle every variant.
Java
Raw
public sealed interface Shape permits Circle, Square, Rectangle {}

public record Circle(double radius)             implements Shape {}
public record Square(double side)               implements Shape {}
public record Rectangle(double w, double h)     implements Shape {}

// The compiler verifies every variant is handled — no `default` needed.
public static double area(Shape s) {
    return switch (s) {
        case Circle c    -> Math.PI * c.radius() * c.radius();
        case Square sq   -> sq.side() * sq.side();
        case Rectangle r -> r.w() * r.h();
    };
}

// With pattern variables + record deconstruction
public static String describe(Shape s) {
    return switch (s) {
        case Circle(double r) when r > 100 -> "huge circle";
        case Circle(double r)              -> "circle r=" + r;
        case Square(double side)           -> "square " + side;
        case Rectangle(double w, double h) -> w == h ? "actually a square" : "rect";
    };
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.