Reading history

Java Sealed Classes and Pattern Matching for switch

6 min read 0 views

Learn sealed interfaces and classes in Java, pattern matching for instanceof and switch, record patterns and when guards, with Java 21 examples.

Modern Java (17 and 21) added three features that work beautifully together. Sealed classes and interfaces let you list exactly which types may extend them. Pattern matching lets instanceof and switch test a type and pull out its data in one step. And the compiler can then check that a switch handles every possible case. The result is shorter code that the compiler double-checks for you.

In this lesson you will learn

  • Declaring a sealed interface with permits
  • Pattern matching for instanceof
  • Type patterns in switch without a default
  • Record patterns that take fields apart
  • Guards with when

You should know interfaces, records and switch expressions. The examples need Java 21 or later.

Sealed Types and Type Patterns

public class Main {
    // Only these three classes may implement Shape
    sealed interface Shape permits Circle, Rect, Triangle {}
    record Circle(double r) implements Shape {}
    record Rect(double w, double h) implements Shape {}
    record Triangle(double base, double height) implements Shape {}

    // Pattern matching in switch: no default needed, the compiler knows every case
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Rect r -> r.w() * r.h();
            case Triangle t -> 0.5 * t.base() * t.height();
        };
    }

    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Rect(3, 4), new Triangle(6, 2) };
        for (Shape s : shapes) {
            System.out.printf("%-30s area = %.2f%n", s, area(s));
        }

        // Pattern matching for instanceof: test and cast in one step
        Object o = new Rect(2, 5);
        if (o instanceof Rect r && r.w() < r.h()) {
            System.out.println("Tall rectangle, width " + r.w());
        }
    }
}

Output

Circle[r=1.0]                  area = 3.14
Rect[w=3.0, h=4.0]             area = 12.00
Triangle[base=6.0, height=2.0] area = 6.00
Tall rectangle, width 2.0
  • sealed interface Shape permits Circle, Rect, Triangle says that these three records are the only shapes. Any other class that tries to implement Shape causes a compile error.
  • Records are automatically final, which a sealed hierarchy requires. A permitted class must be final, sealed or non-sealed.
  • case Circle c -> is a type pattern: if s is a Circle, it is bound to the variable c, already cast.
  • The switch has no default. Because Shape is sealed, the compiler knows the three cases cover everything. If you later add a Hexagon to the permits list, every such switch stops compiling until you handle it.
  • o instanceof Rect r && r.w() < r.h() tests, casts and uses r in one expression. Before Java 16 you needed a separate cast line.

Record Patterns and Guards

public class Main {
    sealed interface Payment permits Cash, Card, Mobile {}
    record Cash(double amount) implements Payment {}
    record Card(double amount, String last4) implements Payment {}
    record Mobile(double amount, String provider) implements Payment {}

    // Record patterns take the fields apart; "when" adds a condition (guard)
    static String describe(Payment p) {
        return switch (p) {
            case Cash(double amt) when amt >= 10000 -> "Large cash payment: " + amt;
            case Cash(double amt) -> "Cash: " + amt;
            case Card(double amt, String last4) -> "Card ending " + last4 + ": " + amt;
            case Mobile(double amt, String provider) -> provider + " payment: " + amt;
        };
    }

    // Made-up fee rules in one place; the compiler checks every payment type is handled
    static double fee(Payment p) {
        return switch (p) {
            case Cash c -> 0;
            case Card c -> c.amount() * 0.015;
            case Mobile m when m.provider().equals("bKash") -> m.amount() * 0.0185;
            case Mobile m -> m.amount() * 0.015;
        };
    }

    public static void main(String[] args) {
        Payment[] payments = {
            new Cash(500), new Cash(25000), new Card(1200, "4821"),
            new Mobile(800, "bKash"), new Mobile(800, "Nagad")
        };
        for (Payment p : payments) {
            System.out.printf("%-30s fee %.2f%n", describe(p), fee(p));
        }
    }
}

Output

Cash: 500.0                    fee 0.00
Large cash payment: 25000.0    fee 0.00
Card ending 4821: 1200.0       fee 18.00
bKash payment: 800.0           fee 14.80
Nagad payment: 800.0           fee 12.00
  • case Cash(double amt) is a record pattern. It checks the type and unpacks the record’s components into variables in one step.
  • when amt >= 10000 is a guard: the case matches only if the condition is true. Cases are checked from top to bottom, so the guarded case must come before the plain Cash case.
  • In fee, bKash payments get one rate and other mobile payments another. The fee rules are made up for the example, but the shape of the code is how real rule tables look.
  • Adding a new payment type, such as Cheque, makes both describe and fee fail to compile until each one handles it. Nothing is silently forgotten.

Before and After

Old styleModern style
if (o instanceof Rect) { Rect r = (Rect) o; ... }if (o instanceof Rect r) { ... }
Chain of if/else instanceof checksswitch with type patterns
default branch that “should never happen”Sealed type: the compiler proves every case is handled
Calling getters after a castRecord patterns unpack the fields directly

Common Mistakes

  1. Putting a general case before a guarded one. case Cash c above case Cash c when ... makes the guarded case unreachable, which is a compile error.
  2. Forgetting that permitted classes must be final, sealed or non-sealed. A plain class in the permits list will not compile.
  3. Adding default to a switch over a sealed type. It compiles, but it hides new subtypes, which removes the main benefit.
  4. Using an older Java version. Pattern matching for switch and record patterns are final from Java 21.

Practice Exercises

Exercise 1. Add a Square(double side) record to the shapes and update area.

Show answer
sealed interface Shape permits Circle, Rect, Triangle, Square {}
record Square(double side) implements Shape {}
// in area():
case Square sq -> sq.side() * sq.side();

Until you add the new case, the compiler reports that the switch does not cover all possible values.

Exercise 2. Write isBig(Shape s) that returns true for circles with radius over 5 and rectangles with either side over 10, and false otherwise.

Show answer
static boolean isBig(Shape s) {
    return switch (s) {
        case Circle(double r) when r > 5 -> true;
        case Rect(double w, double h) when w > 10 || h > 10 -> true;
        default -> false;
    };
}

Here default is fine, because “everything else” really is the intended meaning.

Frequently Asked Questions

What is the difference between sealed classes and enums?

An enum has a fixed set of instances, such as RED and GREEN. A sealed type has a fixed set of subtypes, and each subtype can have many instances with different data, like circles of different sizes.

Do the permitted classes have to be in the same file?

No. They must be in the same package (or the same module). If they are in the same file as the sealed type, you can leave out the permits clause and the compiler works it out.

Summary

  • sealed ... permits fixes the list of subtypes.
  • instanceof Type name tests and casts in one step.
  • switch type patterns over a sealed type need no default.
  • Record patterns unpack fields; when adds a condition.

Next: BigDecimal and BigInteger in Java.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *