Designing with Sealed Classes
summary
Sealed classes in modern Java close inheritance for plugin-style APIs so core abstractions can be public but not extensible, replacing brittle hacks like package-private constructors, runtime instanceof checks, or custom annotation processors. Example: a sealed TrafficLight with three permitted leaves (Red, Yellow, Green) compiles to bytecode that records permitted subclasses and the compiler rejects unauthorized subclasses at compile time; reflection exposes getPermittedSubclasses, and using sealed + final yields exhaustiveness for pattern matching. Modules widen where permitted subclasses may live.
AI-written summary · about
chapters (8)
- 0:00Introduction to sealed classes
- 7:27Why restrict inheritance
- 16:45Hacky solutions for inheritance
- 26:38Sealed classes explained
- 38:09Practical sealed class example
- 45:54Non-sealed classes and use cases
- 57:05Reflection and pattern matching
- 1:00:16Summary and best practices
related talks
38mEnums on steroids - let's look at sealed classes !
18mEnums on steroids - let's look at sealed classes!
43mEnums on steroids - let's look at sealed classes!
39mJava 16 Language Features
01h 02mThe Three Amigos: Intermixing Pattern Matching, Records, and Sealed Classes
27mModern Java API Design
02h 41mCruising Along with Java: Benefiting from the Modern Features
40mSailing Java 16
