Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

sealed / permits

Restricts which classes may extend a class or implement an interface.

Available since: Java 17

Syntax

sealed interface Name permits A, B { }

Examples

A closed hierarchy and a switch without default:

sealed interface Shape permits Circle, Rect {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
 
double area(Shape s) {
    return switch (s) {
        case Circle c -> Math.PI * c.r() * c.r();
        case Rect r -> r.w() * r.h();
    };
}
 
void main() {
    IO.println(area(new Rect(2, 3)));
}

Output:

6.0

Notes

Each permitted subclass must be final, sealed or non-sealed (records and enums are already final). If the subclasses are in the same file, permits can be omitted — the compiler finds them.

The main benefit is that the compiler knows every case: a switch over such a type needs no default, and adding a new subclass makes the compiler point at every place that must handle it.

See also

  • switch — Picks a branch by value; as an expression it returns a result.
  • record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().
  • interface — Declares an interface — a set of methods that a class promises to implement.
  • final — Forbids reassigning a variable, overriding a method or extending a class.

In the tutorial

  • Sealed classes — Sealed classes and interfaces in Java: sealed, permits, final and non-sealed subclasses and a switch without a default branch.

Thanks for reading!

Donate to the site — we work hard for you.