Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

sealed — restricted type hierarchy

sealed — restricted type hierarchy: sealed restricts a class or interface’s direct subtypes to those named by permits or inferred in the same compilation unit.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

sealed

sealed restricts a class or interface’s direct subtypes to those named by permits or inferred in the same compilation unit.

Use sealed with permits for a closed domain; a direct subtype is explicitly or implicitly final, sealed, or non-sealed. A record is implicitly final, while an enum may be implicitly final or sealed.

A permitted subtype must directly extend or implement the sealed type and reside in the same module, or in the same package when in an unnamed module.

permits may be omitted only when suitable direct subtypes occur in the same compilation unit; reflection exposes them through getPermittedSubclasses.

getPermittedSubclasses reveals exactly Circle and Polygon, while true confirms that record Circle is final as a direct sealed subtype.

Examples

import java.util.Arrays;

public class Main {
    sealed interface Shape permits Circle, Polygon {}
    record Circle(int radius) implements Shape {}
    non-sealed static class Polygon implements Shape {}

    public static void main(String[] args) {
        var names = Arrays.stream(Shape.class.getPermittedSubclasses())
                .map(Class::getSimpleName)
                .sorted()
                .toList();
        System.out.println(names);
        System.out.println(java.lang.reflect.Modifier.isFinal(Circle.class.getModifiers()));
    }
}

Result

[Circle, Polygon]
true

getPermittedSubclasses reveals exactly Circle and Polygon, while true confirms that record Circle is final as a direct sealed subtype.

Sources