Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 18 - Modern Java Features 8 to 21

Java 15 Sealed Classes for Restricted Hierarchy

Reviewed & accurate
AI Summary

Introduction

Java 15, released in September 2020, introduced sealed classes as a preview language feature under JEP 360. A sealed class is a class that explicitly declares which other classes are allowed to extend it. Before Java 15, the only ways to control inheritance were final (no subclasses at all) or open (any subclass, anywhere, anytime). Java 15 sealed classes introduced the middle ground: the class is open to a closed set of permitted subclasses, and the compiler enforces the closure at compile time. The feature was refined in Java 16 (JEP 397) and finalised in Java 17 (JEP 409).

For a Java learner, java 15 sealed classes is the gateway to writing algebraic data types in Java. Sealed classes pair naturally with records (finalised in Java 16) and pattern matching for switch (finalised in Java 21), letting the compiler verify that a switch expression over a sealed hierarchy is exhaustive without a default arm. This post walks through the sealed and permits syntax, the rules for permitted subclasses, and the integration with records and switch expressions.

What is Java 15 Sealed Classes?

A sealed class is declared with the modifiers sealed and permits. The sealed keyword tells the compiler that the class is open only to a specific list of subclasses; the permits clause lists those subclasses by name. For example, public sealed class Shape permits Circle, Square, Triangle {} declares that Shape can be extended only by Circle, Square, and Triangle. Each permitted subclass must be declared in the same source file or the same package (in Java 17+, also the same module), and each must have one of three modifiers: final (cannot be extended further), sealed (can be extended only by its own permitted subclasses), or non-sealed (open to any subclass, breaking the closure below this point).

Conceptually, sealed classes belong to the family of restricted-inheritance constructs, similar to Kotlin's sealed classes, Scala's sealed traits, and Swift's final-by-default classes. The key property is that the compiler can enumerate every permitted subclass at compile time, which enables exhaustive pattern matching: a switch expression over a sealed hierarchy with one arm per permitted subclass needs no default case, because the compiler knows the arms cover every possible value.

How Java 15 Sealed Classes Works - Step by Step

Step 1: Declare the sealed class with the permits clause. The permits clause lists every permitted subclass by simple name (when in the same file) or by fully qualified name (when in a different file). The order of the permits list does not matter.

Step 2: Declare each permitted subclass in the same file or the same package. Each subclass must extend the sealed class and must have one of three modifiers: final, sealed (with its own permits clause), or non-sealed. The compiler rejects any subclass that does not match the sealed class's permits list or that lacks one of the three required modifiers.

Step 3: Use the sealed class as a base type. Variables of type Shape can hold any instance of the permitted subclasses: Circle, Square, or Triangle. The compiler knows at compile time that no other subclass of Shape exists.

Step 4: Switch over the sealed hierarchy. A switch expression that has one arm per permitted subclass is exhaustive without a default case. The compiler knows that no other subclass can exist, so it accepts the switch as complete. If you add a new permitted subclass to the sealed class, the switch must be updated, or the compiler will emit an error.

Step 5: Combine with records for algebraic data types. A common idiom is to declare the sealed class with a permits clause that lists only record subclasses. Because records are implicitly final, the records cannot be extended further, and the closure is tight. This is the Java equivalent of Scala's sealed trait plus case class hierarchy.

Java Program for Sealed Classes

import java.util.List;

public class SealedClassDemo {

    // (1) Sealed hierarchy with three record subclasses
    public sealed interface Shape
            permits Circle, Square, Triangle {}

    public record Circle(double r) implements Shape {}
    public record Square(double side) implements Shape {}
    public record Triangle(double a, double b, double c) implements Shape {}

    // (2) A non-sealed subclass that opens the closure below it
    public sealed interface Tree permits Leaf, Branch {}
    public record Leaf(int value) implements Tree {}
    public non-sealed class Branch implements Tree {
        public final Tree left, right;
        public Branch(Tree left, Tree right) {
            this.left = left; this.right = right;
        }
    }

    // (3) Exhaustive switch with no default arm
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Square sq -> sq.side() * sq.side();
            case Triangle t -> {
                double sp = (t.a() + t.b() + t.c()) / 2.0;
                yield Math.sqrt(sp * (sp - t.a())
                        * (sp - t.b()) * (sp - t.c()));
            }
        };
    }

    // (4) Recursive processing of the Tree hierarchy
    static int sum(Tree t) {
        if (t instanceof Leaf l) {
            return l.value();
        }
        if (t instanceof Branch b) {
            // Branch is non-sealed, so we may have arbitrary
            // subclasses of Branch; in this demo we only use the
            // concrete Branch record-like class above.
            return sum(b.left) + sum(b.right);
        }
        // exhaustive because Leaf and Branch are the only permitted
        // direct subclasses of Tree, but Branch itself is non-sealed
        // so subclasses outside this file are possible; that means
        // this else branch is reachable at runtime for unknown
        // subclasses of Branch.
        throw new IllegalStateException("unknown Tree: " + t);
    }

    // (5) Exhaustive switch on Tree with pattern matching (Java 21)
    static String describe(Tree t) {
        return switch (t) {
            case Leaf l -> "leaf(" + l.value() + ")";
            case Branch b -> "branch(" + describe(b.left)
                    + ", " + describe(b.right) + ")";
            // No default needed for the sealed interface Tree
        };
    }

    public static void main(String[] args) {
        // (1) Three shapes
        List<Shape> shapes = List.of(
                new Circle(2.0), new Square(3.0),
                new Triangle(3.0, 4.0, 5.0));
        double total = 0;
        for (Shape s : shapes) total += area(s);
        System.out.println("(1) total area: " + total);

        // (2) Tree hierarchy
        Tree tree = new Branch(
                new Leaf(1),
                new Branch(new Leaf(2), new Leaf(3)));
        System.out.println("(2) sum: " + sum(tree));
        System.out.println("(2) describe: " + describe(tree));

        // (3) Test triangle area
        Triangle t = new Triangle(3.0, 4.0, 5.0);
        System.out.println("(3) triangle area: " + area(t));

        // (4) Square that goes through the switch
        System.out.println("(4) square area: " + area(new Square(5.0)));

        // (5) Circle area
        System.out.println("(5) circle area: " + area(new Circle(1.0)));

        // (6) Exhaustive switch on small tree
        Tree leaf = new Leaf(42);
        System.out.println("(6) leaf describe: " + describe(leaf));

        // (7) Bigger tree with mixed leaves and branches
        Tree bigTree = new Branch(
                new Branch(new Leaf(10), new Leaf(20)),
                new Branch(new Leaf(30), new Leaf(40)));
        System.out.println("(7) bigTree sum: " + sum(bigTree));
        System.out.println("(7) bigTree describe: " + describe(bigTree));
    }
}

Code Explanation - Line by Line

Section (1) declares a sealed interface Shape with three permitted record subclasses: Circle, Square, and Triangle. Using an interface instead of a class for the sealed base is the modern idiom because interfaces support multiple inheritance and records can implement multiple interfaces. Each record is implicitly final, so the closure of permitted subclasses of Shape is exactly Circle, Square, and Triangle.

Section (2) declares a sealed interface Tree with two permitted subclasses: the record Leaf and the non-sealed class Branch. Because Branch is non-sealed, it can be extended by any class anywhere, but Branch itself is still a permitted direct subclass of Tree. The recursive structure (Branch contains two Tree references) lets us model binary trees of arbitrary depth.

Method (3) area is the canonical exhaustive switch expression. The switch has one arm per permitted subclass of Shape: Circle, Square, and Triangle. There is no default arm because the compiler knows the switch is exhaustive. If you later added a Rectangle subclass to the permits list of Shape without updating the area method, the compiler would emit an error: "the switch expression does not cover all possible input values". This is the central safety win of sealed classes.

Method (4) sum uses instanceof pattern matching on Tree. The two if branches handle Leaf and Branch. Because Branch is non-sealed, the else branch is reachable in principle (an unknown subclass of Branch from outside this file), so we throw an IllegalStateException for safety. In a real codebase where Branch is final or sealed itself, the else branch would be unreachable, and you could remove it.

Method (5) describe is the Java 21 pattern matching for switch applied to a sealed hierarchy. The switch has one arm per permitted direct subclass of Tree, and the compiler verifies exhaustiveness without a default case. Because Tree is sealed with only Leaf and Branch as direct permitted subclasses, and the Branch arm covers all Branch subclasses (including any non-sealed extensions), the switch is exhaustive.

Section (1) in main computes the total area of three shapes: a Circle with r=2 (area PI*4), a Square with side=3 (area 9), and a Triangle with sides 3, 4, 5 (a right triangle, area = 6). The total is PI*4 + 9 + 6 = approximately 12.566 + 9 + 6 = 27.566. The exact value will be 4*PI + 15 = 12.566370614359172 + 15 = 27.566370614359172.

Section (2) builds a tree Branch(Leaf(1), Branch(Leaf(2), Leaf(3))) and computes its sum (1 + 2 + 3 = 6) and a description string. Section (3) computes the area of the 3-4-5 triangle, which is a right triangle with legs 3 and 4, so area = 3*4/2 = 6. Section (6) tests the describe method on a single leaf. Section (7) builds a larger tree and verifies the recursive sum.

Sample Input and Output

Input:  args = [] (uses fixed demo data)
Output:
(1) total area: 27.566370614359172
(2) sum: 6
(2) describe: branch(leaf(1), branch(leaf(2), leaf(3)))
(3) triangle area: 6.000000000000001
(4) square area: 25.0
(5) circle area: 3.141592653589793
(6) leaf describe: leaf(42)
(7) bigTree sum: 100
(7) bigTree describe: branch(branch(leaf(10), leaf(20)), branch(leaf(30), leaf(40)))

The output confirms that the exhaustive switch expression produces the correct area for each shape kind, that the recursive Tree sum correctly accumulates leaf values, and that the describe method renders the tree structure as a Lisp-like nested string. The triangle area of 6.000000000000001 is the floating-point representation of 6 computed via Heron's formula, which involves a square root that introduces a tiny rounding error.

Common Mistakes to Avoid

The first mistake is forgetting the permits clause on a sealed class. A sealed class without a permits clause is rejected by the compiler unless it has a permitted-subclasses attribute that the compiler can infer (which only happens in some implicit-permits scenarios from Java 17 onward). Always write the permits clause explicitly.

The second mistake is giving a permitted subclass the wrong modifier. Each permitted subclass must have exactly one of three modifiers: final, sealed (with its own permits), or non-sealed. A subclass with no modifier is rejected with "sealed, non-sealed, or final modifiers expected".

The third mistake is putting a permitted subclass in a different package without using the fully qualified name. In Java 15 and 16, permitted subclasses must be in the same package as the sealed class. In Java 17 with modules, they can be in the same module but must be referenced by fully qualified name if in a different package.

The fourth mistake is assuming that the exhaustive switch check on a sealed hierarchy covers non-sealed branches. If a permitted subclass is non-sealed, its own subclasses are unknown, so the switch must include a default arm or the non-sealed subclass arm must handle the case. Only fully sealed or final hierarchies get the strict exhaustive check.

Real-World Applications

In production Java code, sealed classes are heavily used in domain modelling, AST representation, and event sourcing. Spring Framework's ApplicationEvent hierarchy in modern code uses sealed classes to express the closed set of event subtypes. The Jackson JSON library uses sealed classes internally for its token-tree representation, where JsonNode is a sealed base with record subclasses like ObjectNode, ArrayNode, and TextNode.

In build tooling, the Gradle build tool's task-result type is a sealed hierarchy of Success, Failure, and UpToDate. The Maven build tool's lifecycle phase is a sealed enum-like class. Both rely on the exhaustive switch check to ensure that adding a new result type forces updates everywhere the type is switched over.

In compiler and parser code, the abstract syntax tree (AST) types are typically sealed hierarchies of records. The JavaParser library, the Eclipse JDT compiler, and the IntelliJ IDEA PSI tree all use sealed-class-like patterns to model AST nodes. The exhaustive switch check ensures that adding a new AST node type forces updates in every visitor and code generator.

Conclusion

Java 15 sealed classes (finalised in Java 17) introduce the third option for inheritance control: open only to a closed set of permitted subclasses. Combined with records and pattern matching for switch, sealed classes let the compiler verify exhaustive dispatch over an algebraic data type, eliminating a class of missing-case bugs. Next, study Java 16 record patterns to see how the pattern-matching system destructures records, and then read up on Java 17 sealed classes stable to see the final form of the feature.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments