Java / Java 21 Coding Standards Interview Questions
What are sealed classes in Java 21?
A sealed class or interface restricts which other classes are allowed to extend or implement it, using a permits clause that lists the exact set of allowed subtypes.
public sealed interface Shape permits Circle, Square, Triangle {} public final class Circle implements Shape { /* ... */ }
Each permitted subtype must itself be declared final, sealed, or non-sealed, so the hierarchy's shape is fully known at compile time rather than open to arbitrary extension from any package.
Coding standards recommend sealed hierarchies whenever the domain has a fixed, known set of variants - such as payment methods or shape types - because it lets a switch over the type be checked for exhaustiveness by the compiler, catching a missing case at compile time instead of at runtime.
More Related questions...