Object-Oriented Java · 8 min read · Beginner
Rich Enums & Sealed Interfaces
Attach fields and methods to Java enums and model closed domain hierarchies with Java 17+ sealed interfaces.
What you'll learn
- Attach data and behavior directly to Java enum constants
- Restrict which types can implement an interface using sealed ... permits
- Achieve compiler-verified exhaustive switch expressions
Java enum types are full classes: each constant can hold fields and methods. Modern Java also adds sealed interface, letting you declare the exact closed set of permitted subtypes so the compiler guarantees your switch handles every case.
Fill-in-the-Blank Exercise
Sealed Interface Declaration
Declare a sealed Result interface that permits only Ok and Err.
interface Result Ok, Err {}Live Code Lab
JavaEnumsDemo.java
Expected OutputClick “Run Live” to compile with OpenJDK 21
FREE: $0/mo PRO: $19/mo TEAM: $49/mo
Check Your Understanding
Score: 0 / 1
1. What does declaring a sealed interface with permits A, B enforce?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.