liveBook · Manning

Sealed type

As explained in 100 Java Mistakes and How to Avoid Them

A sealed interface is a Java interface that restricts which classes or interfaces may directly implement or extend it.

A sealed interface restricts which classes or interfaces may directly implement or extend it. This creates a closed type hierarchy that can replace chains of instanceof checks with compiler-checked exhaustive processing. section 8.2

Exhaustive processing with a sealed interface

sealed interface Entry {} record IntEntry(int value) implements Entry {} record StringEntry(String value) implements Entry {} void processList(List<Entry> list) { for (Entry element : list) { switch (element) { case IntEntry(int number) -> processNumber(number); case StringEntry(String string) -> processString(string); } } } The compiler checks that the switch covers every permitted Entry type. Adding another inheritor produces a compilation error at the switch, forcing the new case to be handled. section 8.2

Use sealed hierarchies when processing must account for every known variant:

  • Prefer an explicit exhaustive switch over a chain of instanceof checks when the possible types form a closed hierarchy. section 8.2
  • Use an explicit failure branch when unrelated objects may still appear, so unexpected values are easier to investigate. section 8.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines a sealed interface hierarchy and demonstrates compiler-checked exhaustive switching, without detailing broader hierarchy design.
Examples
Uses Entry with IntEntry and StringEntry records to process a list through an exhaustive switch.
What you can do after
Apply via the Java 21 compiler to force handling of newly added inheritors.
How it connects
Connects interfaces, instanceof checks, exhaustive switch statements, records, and deconstruction patterns.

Also explained in

Compare how 2 books explain sealed type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.