Sealed Classes & Interfaces (Java 17)
sealed/permits hierarchy, sealed vs final vs non-sealed, algebraic data types in Java
- Define a closed hierarchy with sealed and permits
- Combine sealed classes with records for algebraic data types
- Use sealed classes as the basis for exhaustive switch
A comprehensive study guide covering the motivation behind sealed types, syntax, rules, subclass modifiers, hierarchy design, and real-world usage patterns introduced in Java 17.
Table of Contents
- The Problem: Lack of Control in Inheritance
- What Are Sealed Classes and Interfaces?
- Why Sealed Types Were Introduced
- Syntax
- The Three Subclass Modifiers:
final,non-sealed,sealed - Rules and Constraints
- Complete Hierarchy Example
- Code Examples
- Sealed Classes vs Sealed Interfaces
- Sealed Types and Pattern Matching / Switch
- Memory & JVM Behavior
- Diagrams
- Comparison: Before and After Sealed Types
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. The Problem: Lack of Control in Inheritance
Overview
Before Java 17, once you declared an interface or a non-final class, anyone could extend or implement it. There was no language-level mechanism to say "only these specific classes are allowed to participate in this hierarchy."
The Unrestricted Hierarchy Problem
Consider a simple Shape interface:
1public interface Shape {2 double area();3}The following classes can all implement Shape with zero restriction:
1class Circle implements Shape { ... }2class Rectangle implements Shape { ... }3class Triangle implements Shape { ... }4class Blob implements Shape { ... } // unplanned!5class Amoeba implements Shape { ... } // unplanned!6// ... anyone can add moreYou have zero control over who joins this hierarchy — including classes added by other engineers that you never anticipated, from entirely different packages or modules.
Why This Causes Problems
◆ 1. Unpredictable `instanceof` / `if-else` Chains
When consuming a Shape, you write defensively:
1void draw(Shape shape) {2 if (shape instanceof Circle c) {3 // handle circle4 } else if (shape instanceof Rectangle r) {5 // handle rectangle6 } else {7 // ← forced to write a catch-all for unknown shapes8 throw new UnsupportedOperationException("Unknown shape: " + shape);9 }10}The else branch only exists because you cannot guarantee what types will appear. This is defensive boilerplate driven by uncertainty, not by design.
◆ 2. Incomplete `switch` Statements
1switch (shape) {2 case Circle c -> drawCircle(c);3 case Rectangle r -> drawRectangle(r);4 default -> { /* forced default */ }5}The compiler requires a default because it cannot know all possible subtypes. If a new subtype is added later and you forget to handle it, the default branch silently runs — potentially hiding a bug.
◆ 3. Silent Runtime Failures
If a new subtype is added and existing switch or if-else code is not updated, the default branch runs silently. The code compiles and runs but produces wrong behavior. This is a silent bug — the hardest kind to diagnose.
◆ 4. No Design Enforcement
You may have carefully designed a hierarchy where only Circle, Rectangle, and Triangle make semantic sense as shapes in your domain. But the language provides no way to enforce this intent. Any engineer (or library user) can subclass freely.
The Root Cause
1Interface / Abstract Class2 ↑ ↑ ↑ ↑3 Circle Rectangle Triangle ??? ← no limit4 ↑5 ??? ← no limit at any levelThe hierarchy is open-ended in every direction with no mechanism to close it.
2. What Are Sealed Classes and Interfaces?
Definition
A sealed class or interface is one that explicitly restricts which other classes or interfaces may directly extend or implement it. The allowed subtypes are declared using the permits clause.
1public sealed interface Shape permits Circle, Rectangle, Triangle { }This declaration means:
Shapecan be subtyped — it is notfinal.- Only
Circle,Rectangle, andTrianglemay directly implementShape. - Any other class attempting to implement
Shapewill cause a compile-time error.
Version Introduction
| Feature | JDK Version |
|---|---|
| Sealed classes (Preview) | Java 15 |
| Sealed classes (Second Preview) | Java 16 |
| Sealed classes (Standard/GA) | Java 17 |
3. Why Sealed Types Were Introduced
| Goal | How Sealed Types Help |
|---|---|
| Controlled inheritance | Only listed classes may extend/implement |
| Exhaustive type checking | Compiler knows all subtypes → no forced default |
| Design intent as code | The permits clause documents which types are valid |
| Better pattern matching | Works with switch expressions for exhaustive, safe dispatch |
| API stability | Library authors can expose a type hierarchy without allowing users to extend it arbitrarily |
Real-World Analogy
Think of a sealed class like a franchise agreement. A parent company (the sealed class) defines exactly which franchise owners (permitted subclasses) are allowed to operate. No new franchisee can open a branch without being named in the agreement. The franchise structure is closed by design, not by accident.
4. Syntax
Sealed Interface
1public sealed interface Shape permits Circle, Rectangle, Triangle {2 double area();3}Sealed Class
1public sealed class Vehicle permits Car, Truck, Motorcycle {2 // common fields and methods3}Sealed Abstract Class
1public sealed abstract class AbstractShape permits Rectangle, Triangle {2 public abstract double area();3 public abstract double perimeter();4}Syntax Breakdown
| Keyword / Element | Role |
|---|---|
sealed | Declares that this type restricts its subtypes |
permits | Introduces the list of allowed direct subtypes |
Circle, Rectangle, ... | Comma-separated list of permitted subtype names |
| Each permitted subtype | Must itself be declared final, sealed, or non-sealed |
permits list must be in the same package (or the same named module) as the sealed type, and must directly extend/implement the sealed type.5. The Three Subclass Modifiers: `final`, `non-sealed`, `sealed`
Every class named in a permits list must be declared with exactly one of these three modifiers. This is mandatory — omitting the modifier causes a compile-time error.
5.1 `final` Close the Branch
1public final class Circle implements Shape {2 private final double radius;3 // ...4}Meaning: No further subclassing allowed. Circle is a leaf in the hierarchy. This is the end of this branch.
Use when: The type is fully concrete and no meaningful specialization of it should ever exist.
5.2 `non-sealed` Open the Branch
1public non-sealed interface Polygon extends Shape {2 int sides();3}Meaning: This subtype is open to any further subclass, without restriction. It abandons the sealed constraint for its own subtree.
Use when: You want the sealed type to be controlled, but you intentionally want to allow free extension at this particular branch.
non-sealed, the exhaustiveness guarantee is lost for that branch. Pattern matching over Shape would still need a default or a catch-all for the Polygon branch.5.3 `sealed` (with further `permits`) Control the Next Level
1public sealed abstract class AbstractShape implements Shape2 permits Rectangle, Triangle {3 // ...4}Meaning: This subtype is itself sealed — it restricts its own subclasses to a specific list.
Use when: You want to carry the sealed constraint further down the hierarchy, controlling multiple levels.
Summary Table
| Modifier | Further subclassing | Who can subclass | Exhaustiveness preserved? |
|---|---|---|---|
final | ❌ Not allowed | Nobody | ✅ Yes |
non-sealed | ✅ Unlimited | Anyone | ❌ Lost for this branch |
sealed | ✅ Controlled | Only listed in permits | ✅ Yes (for next level too) |
6. Rules and Constraints
Rule 1: Permitted Types Must Be Direct Subtypes
Every class in the permits list must directly extend or implement the sealed type. Indirect inheritance is not allowed.
1// ❌ WRONG: Circle does not directly implement Shape2public sealed interface Shape permits Circle { }3
4class Intermediate implements Shape { }5class Circle extends Intermediate { } // Circle is NOT a direct child of Shape1// ✅ CORRECT: Circle directly implements Shape2public sealed interface Shape permits Circle { }3
4public final class Circle implements Shape { } // directRule 2: Each Permitted Subtype Must Declare `final`, `sealed`, or `non-sealed`
1// ❌ WRONG: missing modifier on Circle2public sealed interface Shape permits Circle { }3
4public class Circle implements Shape { } // compile error: must be final, sealed, or non-sealed1// ✅ CORRECT2public sealed interface Shape permits Circle { }3
4public final class Circle implements Shape { } // ✓Rule 3: Permitted Types Must Be Present (No Future Classes)
All classes named in the permits list must already exist as compiled classes. You cannot name a class that does not yet exist.
1// ❌ WRONG: if Triangle.java does not exist, this is a compile error2public sealed interface Shape permits Circle, Rectangle, Triangle { }This enforces that the sealed hierarchy is fully defined at compile time — not a placeholder for future work.
Rule 4: Same Package (or Module)
The sealed type and all its permitted subtypes must be in the same package (or, if using the module system, in the same named module).
1// package com.example.shapes2public sealed interface Shape permits Circle, Rectangle { }3
4// ❌ WRONG: Circle is in a different package5// package com.other;6// public final class Circle implements Shape { }Rule 5: `permits` Clause May Be Omitted If All Subtypes Are in the Same File
If all permitted subclasses are defined in the same source file as the sealed type, the permits clause can be omitted and the compiler infers it automatically.
1// Shape.java — all in one file2public sealed interface Shape { } // permits inferred from file3
4final class Circle implements Shape { }5final class Rectangle implements Shape { }permits clause explicitly for clarity.7. Complete Hierarchy Example
Design Goal
1Shape (sealed interface)2├── Circle (final) ← leaf3├── Polygon (non-sealed interface) ← open branch4│ ├── Hexagon5│ ├── Pentagon6│ └── ... (unlimited)7└── AbstractShape (sealed abstract class) ← controlled branch8 ├── Rectangle (final) ← leaf9 └── Triangle (non-sealed) ← open branch10 ├── EquilateralTriangle11 └── ... (unlimited)Code
1// ─────────────────────────────────────────────2// Level 1: Sealed Interface3// ─────────────────────────────────────────────4public sealed interface Shape5 permits Circle, Polygon, AbstractShape {6 double area();7}8
9// ─────────────────────────────────────────────10// Level 2a: final class — closes this branch11// ─────────────────────────────────────────────12public final class Circle implements Shape {13 private final double radius;14
15 public Circle(double radius) {16 this.radius = radius;17 }18
19 @Override20 public double area() {21 return Math.PI * radius * radius;22 }23}24
25// ─────────────────────────────────────────────26// Level 2b: non-sealed interface — opens this branch27// ─────────────────────────────────────────────28public non-sealed interface Polygon extends Shape {29 int sides();30}31
32// Any class can freely implement Polygon33public class Hexagon implements Polygon {34 private final double side;35
36 public Hexagon(double side) { this.side = side; }37
38 @Override39 public int sides() { return 6; }40
41 @Override42 public double area() {43 return (3 * Math.sqrt(3) / 2) * side * side;44 }45}46
47// ─────────────────────────────────────────────48// Level 2c: sealed abstract class — controls this branch further49// ─────────────────────────────────────────────50public sealed abstract class AbstractShape implements Shape51 permits Rectangle, Triangle {52 public abstract double perimeter();53}54
55// ─────────────────────────────────────────────56// Level 3a: final class — closes rectangle branch57// ─────────────────────────────────────────────58public final class Rectangle extends AbstractShape {59 private final double width;60 private final double height;61
62 public Rectangle(double width, double height) {63 this.width = width;64 this.height = height;65 }66
67 @Override68 public double area() { return width * height; }69
70 @Override71 public double perimeter() { return 2 * (width + height); }72}73
74// ─────────────────────────────────────────────75// Level 3b: non-sealed class — opens triangle branch76// ─────────────────────────────────────────────77public non-sealed class Triangle extends AbstractShape {78 private final double a, b, c; // side lengths79
80 public Triangle(double a, double b, double c) {81 this.a = a; this.b = b; this.c = c;82 }83
84 @Override85 public double area() {86 double s = (a + b + c) / 2;87 return Math.sqrt(s * (s - a) * (s - b) * (s - c));88 }89
90 @Override91 public double perimeter() { return a + b + c; }92}93
94// Free subclass of Triangle — allowed because Triangle is non-sealed95public class EquilateralTriangle extends Triangle {96 public EquilateralTriangle(double side) {97 super(side, side, side);98 }99}Attempting to Add an Unauthorized Subclass
1// ❌ COMPILE ERROR: Star is not in Shape's permits list2public final class Star implements Shape {3 public double area() { return 0; }4}5// Error: class is not allowed to implement sealed interface Shape8. Code Examples
Example 1 Basic Sealed Class (Beginner)
1public sealed class Notification permits EmailNotification, SMSNotification, PushNotification {2 public abstract void send(String message);3}4
5public final class EmailNotification extends Notification {6 @Override7 public void send(String message) {8 System.out.println("Email: " + message);9 }10}11
12public final class SMSNotification extends Notification {13 @Override14 public void send(String message) {15 System.out.println("SMS: " + message);16 }17}18
19public final class PushNotification extends Notification {20 @Override21 public void send(String message) {22 System.out.println("Push: " + message);23 }24}Usage:
1Notification n = new EmailNotification();2n.send("Hello!");3// Output: Email: Hello!What this demonstrates: A sealed class with three final permitted subclasses. The hierarchy is completely closed — nobody can add a fourth notification type without modifying the permits clause.
Example 2 Sealed Interface with Mixed Modifiers (Intermediate)
1public sealed interface Result<T> permits Result.Success, Result.Failure {2
3 record Success<T>(T value) implements Result<T> { } // final implicitly (records are final)4
5 record Failure<T>(String error) implements Result<T> { }6}Usage:
1Result<Integer> result = new Result.Success<>(42);2
3// Exhaustive switch — no default needed!4String message = switch (result) {5 case Result.Success<Integer> s -> "Got value: " + s.value();6 case Result.Failure<Integer> f -> "Error: " + f.error();7};8
9System.out.println(message);10// Output: Got value: 42What this demonstrates: Sealed types combine powerfully with records (which are implicitly final) and exhaustive pattern matching.
Example 3 Multi-Level Sealed Hierarchy (Advanced)
1// Sealed base2public sealed interface Expr permits Num, Add, Mul {3 int evaluate();4}5
6// Leaf: a literal number7public record Num(int value) implements Expr {8 @Override9 public int evaluate() { return value; }10}11
12// Leaf: addition of two Expr nodes13public record Add(Expr left, Expr right) implements Expr {14 @Override15 public int evaluate() { return left.evaluate() + right.evaluate(); }16}17
18// Leaf: multiplication of two Expr nodes19public record Mul(Expr left, Expr right) implements Expr {20 @Override21 public int evaluate() { return left.evaluate() * right.evaluate(); }22}Usage:
1// Represents: (2 + 3) * 42Expr expr = new Mul(new Add(new Num(2), new Num(3)), new Num(4));3System.out.println(expr.evaluate()); // Output: 204
5// Exhaustive pattern matching — compiler verifies all cases covered6String describe(Expr e) {7 return switch (e) {8 case Num(int v) -> "Number: " + v;9 case Add(Expr l, Expr r) -> "(" + describe(l) + " + " + describe(r) + ")";10 case Mul(Expr l, Expr r) -> "(" + describe(l) + " * " + describe(r) + ")";11 };12}13
14System.out.println(describe(expr)); // Output: ((2 + 3) * 4)What this demonstrates: An algebraic data type (AST — Abstract Syntax Tree) modelled with sealed interfaces and records. This is a classic use case for sealed types in functional/compiler design.
9. Sealed Classes vs Sealed Interfaces
| Aspect | Sealed Class | Sealed Interface |
|---|---|---|
| Keyword | sealed class | sealed interface |
| Permitted subtypes can be | classes or interfaces | classes or interfaces |
| Can have constructors | Yes | No |
| Can have state (fields) | Yes | Only static final |
| Permitted subtype extends/implements | extends | implements or extends (if subtype is an interface) |
| Abstract methods | Optional | Implicitly abstract (unless default) |
Both are declared with sealed and permits. The primary difference is the same as between any class and interface — it is not a sealed-specific distinction.
10. Sealed Types and Pattern Matching / Switch
The Key Benefit: Exhaustive Switching
Because the compiler knows exactly which subtypes exist for a sealed type, it can verify that a switch expression or statement covers all cases. If all cases are covered, no default is needed.
1// Without sealed — default is REQUIRED2double computeArea(Shape shape) {3 return switch (shape) {4 case Circle c -> Math.PI * c.radius() * c.radius();5 case Rectangle r -> r.width() * r.height();6 default -> throw new UnsupportedOperationException(); // forced7 };8}9
10// With sealed (permits Circle, Rectangle only) — no default needed!11double computeArea(Shape shape) {12 return switch (shape) {13 case Circle c -> Math.PI * c.radius() * c.radius();14 case Rectangle r -> r.width() * r.height();15 // Compiler confirms: these two cover ALL permitted subtypes ✓16 };17}The Safety Guarantee
If you add a new type to the permits list of a sealed type, all switch expressions that are not exhaustive will fail to compile. This forces you to handle the new type explicitly — the silent bug scenario from the old world is eliminated.
1// You add: Triangle to Shape's permits list2// Now all switch expressions over Shape must handle Triangle too3// → Compile error at every unupdated switch → you can't forget it11. Memory & JVM Behavior
Compile-Time Enforcement
Sealed constraints are enforced by the Java compiler, not the JVM at runtime. The compiler checks:
- That the
permitslist is exhaustive and valid. - That each permitted subtype declares
final,sealed, ornon-sealed. - That no unlisted class extends or implements the sealed type.
Class File Metadata
The sealed and permits information is stored in the compiled .class file using two class file attributes (introduced in Java 17):
PermittedSubclassesattribute — lists the binary names of permitted subtypes.Sealedflag in the access flags.
This means if you compile a sealed class and then replace its .class file with a hand-crafted one that removes the PermittedSubclasses attribute, the JVM will not enforce the restriction. The enforcement is primarily at compile time.
Class Loading
Each permitted subtype is a separate class and is loaded independently by the class loader — exactly like non-sealed types. sealed adds no runtime performance overhead.
12. Diagrams
Full Shape Hierarchy
Decision Tree: Which Modifier to Use on a Permitted Subtype?
Before vs After Sealed Types
Mind Map
13. Comparison: Before and After Sealed Types
Before Writing Defensive Code
1// OLD WAY: shape is uncontrolled2void processShape(Shape shape) {3 if (shape instanceof Circle c) {4 // ...5 } else if (shape instanceof Rectangle r) {6 // ...7 } else {8 // ← MUST have this. Could silently do nothing, or throw.9 System.out.println("Unknown shape, skipping.");10 }11}Problems:
elsebranch is required and may silently ignore new types.- No compile-time guarantee that all types are handled.
- Engineers can forget to update this when a new subtype is added.
After Exhaustive and Safe
1// NEW WAY: Shape is sealed with permits Circle, Rectangle2void processShape(Shape shape) {3 switch (shape) {4 case Circle c -> drawCircle(c);5 case Rectangle r -> drawRectangle(r);6 // No default needed — compiler verifies exhaustiveness ✓7 }8}Benefits:
- No
defaultrequired. - If
Triangleis added topermits, every non-exhaustiveswitchoverShapefails to compile — you cannot forget to handle it.
14. Interview Notes
Q1: What problem do sealed classes solve?
They solve the lack of control in inheritance. Before sealed types, any class could extend or implement any non-final type. This made it impossible to write exhaustive type checks without default branches that could silently swallow bugs.
Q2: What is the difference between `final` and `sealed`?
final | sealed | |
|---|---|---|
| Further subclassing | Completely forbidden | Allowed, but only for listed types |
| Use case | True leaf — no children at all | Controlled branching |
Q3: What are the three modifiers a permitted subtype must declare?
final, non-sealed, or sealed (with its own permits clause). One of the three is mandatory.
Q4: What happens if you forget to declare one of the three modifiers on a permitted subtype?
Compile-time error: the compiler requires each subtype in the permits list to explicitly declare its stance on further subclassing.
Q5: Can a `non-sealed` class's subclasses implement a sealed interface directly?
No. The non-sealed modifier opens that particular branch, but a class extending a non-sealed subtype is not a direct implementor of the sealed interface — it is two levels deep. Only types directly named in permits can be direct subtypes of the sealed type.
Q6: Is the sealed constraint enforced at runtime or compile time?
Primarily at compile time by the Java compiler. The information is stored in the .class file's PermittedSubclasses attribute, and some runtime checking occurs during class loading, but the main enforcement gate is the compiler.
Q7: How do sealed types interact with `switch` pattern matching?
The compiler knows the complete set of subtypes for a sealed type. A switch expression that covers all permitted subtypes is considered exhaustive and requires no default arm. Adding a new type to permits causes every non-exhaustive switch to fail compilation.
Q8: Can the `permits` clause be omitted?
Yes, if all permitted subtypes are declared in the same source file as the sealed type. The compiler infers the permits list from the classes in that file.
Q9: Can an interface be in a `permits` list?
Yes. A sealed interface can permit another interface (which must then itself be declared sealed or non-sealed).
Q10: What is the typical use case for sealed types in real applications?
- Result / Either types (Success or Failure) — common in functional-style Java.
- Domain models where only known variants are valid (payment method types, notification channels, etc.).
- ASTs / expression trees in interpreters and compilers.
- State machines where states are a closed, known set.
15. Common Mistakes
Mistake 1: Forgetting the Modifier on a Permitted Subtype
1// ❌ WRONG: Circle has no modifier2public sealed interface Shape permits Circle { }3
4public class Circle implements Shape { } // compile error1// ✅ CORRECT2public final class Circle implements Shape { }Mistake 2: Naming a Non-Direct Subtype in `permits`
1// ❌ WRONG: Ellipse is not a direct implementor of Shape2public sealed interface Shape permits Ellipse { }3
4public abstract class Oval implements Shape { }5public final class Ellipse extends Oval { } // Ellipse is not a direct child of Shape6// compile error: Ellipse is not a direct subtype of Shape1// ✅ CORRECT: list the direct subtype2public sealed interface Shape permits Oval { }3
4public non-sealed abstract class Oval implements Shape { }5public final class Ellipse extends Oval { } // now this is fineMistake 3: Naming a Class That Doesn't Exist Yet
1// ❌ WRONG: Triangle.java does not exist2public sealed interface Shape permits Circle, Rectangle, Triangle { }3// compile error: cannot find class TriangleAll classes in permits must have existing implementations.
Mistake 4: Putting Permitted Subtypes in a Different Package
1// package com.example.shapes2public sealed interface Shape permits Circle { }3
4// package com.other ← WRONG PACKAGE5public final class Circle implements Shape { } // compile errorSealed type and permitted types must share the same package (or named module).
Mistake 5: Adding `default` to a Switch That Doesn't Need One
1// ⚠️ UNNECESSARY (compiles, but defeats the purpose)2switch (shape) {3 case Circle c -> ...;4 case Rectangle r -> ...;5 default -> ...; // redundant — and hides future missing cases6}Without default, adding a new type to permits causes a compile error here — that's the safety net. Adding default turns that compile error back into a silent runtime issue.
16. Best Practices
- Use
finalas the default modifier for permitted subtypes unless you have a specific reason to allow further subclassing. Prefer closed hierarchies.
- Combine with
recordtypes. Records are implicitlyfinaland work perfectly as permitted subtypes for value-based hierarchies:
1 sealed interface Command permits Command.Start, Command.Stop {2 record Start(String name) implements Command { }3 record Stop() implements Command { }4 }- Avoid
non-sealedunless intentionally designing an open extension point. Usingnon-sealedpartially re-introduces the problem sealed types were designed to solve.
- Leverage exhaustive
switchexpressions. The main payoff of sealed types is eliminatingdefault. Write exhaustive switches to get compile-time safety.
- Keep the hierarchy shallow. Deep multi-level sealed hierarchies become hard to reason about. Prefer a flat or two-level design.
- Use sealed types for domain-closed concepts — types where the full set of variants is known and stable. Payment methods, shape kinds, AST nodes, state machine states — these are good candidates. Avoid sealing types where extension by library users is a legitimate use case.
- Document the reason for
non-sealedwith a comment when you use it, since it is an intentional deviation from the controlled hierarchy.
17. Practice Questions
Easy
- What keyword is used to declare a sealed class or interface?
- What keyword introduces the list of permitted subtypes?
- Name the three modifiers a permitted subtype must use.
- Can a class from a different package be in the
permitslist? - Write a sealed interface
Animalthat permits onlyDogandCat.
Medium
- What happens at compile time if you try to implement a sealed interface from a class not in its
permitslist? - Explain why
non-sealedpartially defeats the purpose of sealing a type. When is it still appropriate? - Rewrite the following uncontrolled hierarchy as a properly sealed hierarchy:
1 interface Payment { }2 class CreditCard implements Payment { }3 class BankTransfer implements Payment { }4 class Crypto implements Payment { }- Given a sealed interface
Shapethat permitsCircle(final) andRectangle(final), write an exhaustiveswitchexpression that returns the area without adefaultarm. - Why is omitting
defaultfrom an exhaustive switch over a sealed type safer than including it?
Hard
- Design a sealed class hierarchy to represent a simple expression language with: integer literals, addition, subtraction, and multiplication. All leaf nodes should be
final. Implement anevaluate()method in each. - A sealed interface
ResultpermitsSuccessandFailure. Implement it using records and demonstrate exhaustive pattern matching in a method that returns aStringin both cases. - Explain with a code example how sealed types + pattern matching eliminates the need for the Visitor design pattern in certain scenarios.
- A team adds
Triangleto a sealedShape'spermitslist. Describe the exact sequence of compile errors that will appear across the codebase and how a developer should resolve them systematically. - Compare sealed classes to
enumtypes. In what scenarios would you choose one over the other? What can sealed classes express that enums cannot?
18. Summary
Key Bullet Points
- Sealed types restrict which classes may directly extend or implement them, using
sealed+permits. - Introduced as a standard feature in Java 17 (previewed in Java 15 and 16).
- The core problem solved: uncontrolled inheritance where any class could join a hierarchy silently.
- Every class in the
permitslist must be declaredfinal,non-sealed, orsealed— one of the three is mandatory. final— closes the branch. No further subclasses.non-sealed— opens the branch. Any class may subclass freely from this point.sealed+ furtherpermits— controls the next level of the hierarchy.- Permitted subtypes must be direct subtypes (not transitively indirect) of the sealed type.
- All classes listed in
permitsmust exist at compile time — no placeholders. - Sealed types and permitted subtypes must be in the same package (or same named module).
permitscan be omitted when all subtypes are in the same source file.- The biggest practical benefit: exhaustive
switchexpressions — the compiler verifies all cases are covered, eliminating forceddefaultbranches. - Adding a new type to
permitscauses every non-exhaustiveswitchto fail at compile time — impossible to silently miss a new variant. - Pairs naturally with records (implicitly
final) and pattern matching (Java 16+).
End of Chapter — Java Sealed Classes and Interfaces (Java 17)
Mastery check
How well can you recall this?
Finished this lesson?