Sealed classes
A sealed class or interface restricts which types may extend or implement it. You list the permitted subtypes. The compiler then knows the full set.
Detailed Explanation
Open inheritance means anyone, in any package, can extend your class. That is useful for ArrayList. It is a problem when you model a closed set of cases: a JSON value is an object, array, string, number, boolean, or null. You do not want a seventh type from a dependency. Sealed types (Java 17) let you publish the parent and name the children.
Write sealed class Expr permits Literal, Add. Each permitted type must extend the sealed type, must be in the same module (or the same package if there is no module), and must declare itself final, sealed, or non-sealed. final closes that branch. sealed continues the list one level down. non-sealed opens that branch again, which is an escape hatch you should use rarely.
Sealed interfaces work the same way and pair well with records. sealed interface Shape permits Circle, Rect plus two records is a small algebraic type. Switch expressions can be exhaustive: if you cover every permitted subtype, you need no default. Add a subtype later and every switch fails to compile. That is the feature earning its keep.
You reach for sealed types when the set of variants is part of the API, when you want exhaustive switches, or when you must prevent third parties from inventing subclasses that break invariants (a Money hierarchy that only you implement). You avoid them when libraries and applications are supposed to add implementations: List, Executor, and most plugin points stay open.
The cost is friction when the set was not actually closed. Adding a permitted type is a source-breaking change for every exhaustive switch. Putting all permitted types in one package can crowd that package. Crossing package boundaries requires an explicit module or package arrangement; you cannot seal a type and permit a class in a random third-party jar.
non-sealed exists for migration and for a known extension point under a closed parent. It undoes exhaustiveness for that branch. If you need that often, the type should not have been sealed.
Code Examples
sealed interface Json permits JNull, JBool, JNum, JStr {}
final class JNull implements Json {}
record JBool(boolean value) implements Json {}
record JNum(long value) implements Json {}
record JStr(String value) implements Json {}
public class JsonPrint {
static String show(Json j) {
return switch (j) {
case JNull n -> "null";
case JBool b -> Boolean.toString(b.value());
case JNum n -> Long.toString(n.value());
case JStr s -> s.value();
// no default: the compiler knows the set is complete
};
}
public static void main(String[] args) {
System.out.println(show(new JNum(7))); // prints: 7
}
}sealed class Result<T> permits Ok, Err {}
final class Ok<T> extends Result<T> {
final T value;
Ok(T value) {
this.value = value;
}
}
final class Err<T> extends Result<T> {
final String message;
Err(String message) {
this.message = message;
}
}
public class Results {
static String label(Result<String> r) {
return switch (r) {
case Ok<String> o -> o.value;
case Err<String> e -> "err:" + e.message;
};
}
public static void main(String[] args) {
System.out.println(label(new Ok<>("ok"))); // prints: ok
}
}Common Gotchas
Permitted types must be accessible and actually extend the sealed type
a typo in `permits` is a compile error, not a runtime miss.
Adding a permitted subtype breaks exhaustive switches
that is intended. Plan the set before you publish the parent.
`non-sealed` reopens a branch
switches on the parent then need a `default`, because unknown subclasses can appear.
All permitted types must live in the same module
without a module, they must share a package.