Build a chained sealed hierarchy: Vehicle permits Car and Truck, Car permits Sedan and Hatchback.
← Sealed Types and Traits · Ref: Q1172
Chain 'allow only' at each level:
Vehicle allow only Car, Truck, Sedan, Hatchback as open Car extends Vehicle allow only Sedan, Hatchback as open Sedan extends Car Truck extends Vehicle
Each sealed class lists ALL permitted descendants in its own 'allow only'. The compiler enforces at both levels.
See Q1171 for basic sealed class. See Q303 for chained sealing.
Example
defines module qa.sealedtraits.sealedclasshierarchy defines class Vehicle allow only Car, Truck, Sedan, Hatchback as open describe() <- rtn as String: "Vehicle" Car extends Vehicle allow only Sedan, Hatchback as open override describe() <- rtn as String: "Car" Sedan extends Car override describe() <- rtn as String: "Sedan" Hatchback extends Car override describe() <- rtn as String: "Hatchback" Truck extends Vehicle override describe() <- rtn as String: "Truck" defines program SealedClassHierarchyDemo() stdout <- Stdout() sedan <- Sedan() hatchback <- Hatchback() truck <- Truck() stdout.println(sedan.describe()) stdout.println(hatchback.describe()) stdout.println(truck.describe())
Common mistakes
E05240 — The top-level sealed class must list ALL descendants, including indirect ones (Sedan, Hatchback) — not just direct children.
Incorrect:
Vehicle allow only Car, Truck as open
Correct:
Vehicle allow only Car, Truck, Sedan, Hatchback as open
Other ways to ask this
- Create a multi-level sealed class tree with transitive allow only
- I need Vehicle sealed to Car/Truck, and Car itself sealed to Sedan/Hatchback
- In Java 17 I'd chain sealed permits. Write the EK9 multi-level sealed hierarchy
- Given a two-level hierarchy, seal both levels with their own allow only lists
Coming from another language?
Java 17: sealed class Vehicle permits Car, Truck; sealed class Car extends Vehicle permits Sedan. Kotlin: nested sealed classes. EK9: chained 'allow only' at each level.
Keywords: hierarchy, transitive, chained, allow only, multi-level, sealed