Sub topic 2
Where Permitted Subclasses Can Live
Assume you know Java inheritance, records, enums, switch expressions, and basic modules. A sealed type controls its direct subclasses. The subclasses must follow Java’s location rules:
- In a named module, the sealed type and every permitted subclass must be in the same module.
- In the unnamed module, they must be in the same package.
- If all permitted subclasses are declared in the same compilation unit, Java can infer the permitted list. This is common with nested records.
Records and Enums as Permitted Subtypes
Records are implicitly final, so they can directly implement a sealed interface without writing final. Enum classes are also implicitly final. An enum can implement a sealed interface, but it cannot extend a sealed class because every enum already extends Enum.
public class Main {
sealed interface Token permits Word, Kind {}
record Word(String text) implements Token {}
enum Kind implements Token {
START, END
}
public static void main(String[] args) {
System.out.println(new Word("hello"));
System.out.println(Kind.START);
}
}When nested permitted types are declared in the same compilation unit, omit permits:
sealed interface Shape {
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
}Exhaustive Switch Without `default`
A pattern-matching switch is exhaustive when it covers every permitted subtype. Java 21 can therefore reject a missing case at compile time. No default branch is needed.
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
};
}Adding a new permitted subtype can make existing switches fail to compile. That failure identifies code that needs updating.
Record Patterns in Switch
Record patterns deconstruct a record directly in a case. The pattern binds each component to a local variable.
sealed interface Expr {
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
}
static int eval(Expr expression) {
return switch (expression) {
case Expr.Num(int value) -> value;
case Expr.Add(Expr left, Expr right) ->
eval(left) + eval(right);
};
}Exercise
Why does record Circle(...) implements Shape satisfy the modifier rule for a permitted subtype?
Show answer
Records are implicitly final, so they cannot be extended further.