Core Java

core17SealedClassesDemo

Path
pkg1core/core17SealedClassesDemo.java
Package
pkg1core
Study order
18
Run
Single-file source launch
Command
java pkg1core/core17SealedClassesDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core17SealedClassesDemo.java
1package pkg1core;2 3/*4 * core17SealedClassesDemo.java5 * ----------------------6 * Sealed classes/interfaces (Java 17+): restrict which types may extend/implement,7 * enabling exhaustive pattern matching.8 *9 * EXPLANATION:10 *  - `sealed ... permits A, B` lists the only allowed subtypes.11 *  - Subtypes must be `final`, `sealed`, or `non-sealed`.12 *  - With a sealed hierarchy, a switch can be EXHAUSTIVE without a default.13 */14public class core17SealedClassesDemo {15 16    sealed interface Expr permits Num, Add, Mul {}17    record Num(double value) implements Expr {}18    record Add(Expr left, Expr right) implements Expr {}19    record Mul(Expr left, Expr right) implements Expr {}20 21    // Exhaustive evaluation via pattern matching + record deconstruction22    static double eval(Expr e) {23        return switch (e) {                       // no default needed: sealed + exhaustive24            case Num(double v)        -> v;25            case Add(Expr l, Expr r)  -> eval(l) + eval(r);26            case Mul(Expr l, Expr r)  -> eval(l) * eval(r);27        };28    }29 30    public static void main(String[] args) {31        // (2 + 3) * 432        Expr expr = new Mul(new Add(new Num(2), new Num(3)), new Num(4));33        System.out.println("(2 + 3) * 4 = " + eval(expr));34 35        Expr nested = new Add(new Num(10), new Mul(new Num(2), new Num(2.5)));36        System.out.println("10 + (2 * 2.5) = " + eval(nested));37    }38}