Codectionary / Developer documentation / Java

Sealed Classes and Interfaces

Restrict which types directly extend a class or implement an interface.

What it is and why to use it

A sealed hierarchy models a controlled set of alternatives, such as payment outcomes or document kinds. Introduced as a standard feature in Java 17, sealed lets the author name permitted direct subtypes instead of allowing unrelated code to extend the hierarchy freely.

How it works

permits lists direct subtypes. Each permitted subtype must continue the restriction with sealed, end it with final, or reopen it with non-sealed. In a named module the permitted types belong to that module; in an unnamed module they belong to the same package. The nested types below keep the demonstration in one file.

Common mistakes and limitations

Do not describe sealed as an access-control or security boundary for untrusted code. It does not make instances immutable. This example deliberately avoids preview pattern-switch syntax.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

sealed interface Result permits Success, Failure {}

Examples

Sealed Classes and Interfaces

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  sealed interface Result permits Success, Failure {}
  static final class Success implements Result {}
  static final class Failure implements Result {}

  public static void main(String[] args) {
    Result result = new Success();
    System.out.println(result instanceof Success);
    System.out.println(result instanceof Failure);
  }
}
  1. Result permits only Success and Failure as its direct implementations.
  2. Both classes are final, so neither can be subclassed.
  3. A Success can be stored in a Result variable; the two instanceof tests show which alternative it represents. The hierarchy controls type extension, not whether objects can contain mutable state.
  4. Expected output: true false

Best practices

  • Use sealed when the domain has a deliberately controlled family of types.
  • Keep public extension points unsealed when third-party implementations are intended.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading