A sealed interface is an interface that restricts which classes or interfaces may directly implement or extend it. By using theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
sealed modifier in conjunction with the permits clause, a sealed interface explicitly defines an exhaustive list of allowed subtypes at compile time, providing strict, compiler-enforced control over the inheritance hierarchy.
Syntax Declaration
To declare a sealed interface, apply thesealed modifier before the interface keyword. Following the interface name (and any generic type parameters), use the permits keyword followed by a comma-separated list of the fully qualified or simple names of the allowed subtypes.
permits clause can be omitted. The Java compiler will automatically infer the permitted subtypes from the file’s contents.
Subtype Constraints and Rules
The Java compiler enforces strict rules on any class or interface listed in thepermits clause of a sealed interface:
- Module and Package Restrictions: Permitted subtypes must reside in the same module as the sealed interface. If the interface is declared in an unnamed module, the permitted subtypes must reside in the same package.
- Direct Implementation: Every permitted subtype must directly implement or extend the sealed interface.
- Mandatory Modifiers: Every permitted subtype must explicitly declare exactly one of three inheritance modifiers to define how the hierarchy continues:
final: Prevents any further extension. (Note: This is only applicable to implementing classes, as interfaces cannot be declaredfinal.)sealed: Continues the restriction, requiring the subtype to define its ownpermitsclause.non-sealed: Re-opens the hierarchy, allowing any unknown class or interface to extend or implement this specific subtype.
Subtype Implementation Examples
The following code demonstrates how permitted subtypes must apply the mandatory modifiers when implementing or extending a sealed interface:Integration with Record Classes
Java Records are implicitlyfinal. When a record implements a sealed interface, it satisfies the mandatory modifier requirement without needing an explicit final declaration.
Master Java with Deep Grasping Methodology!Learn More





