Sub topic 1
Java Sealed Classes and Interfaces: Controlling Who Can Extend Your Types
Prerequisites
This chapter assumes you know Java classes, inheritance, interfaces, access modifiers, and final. You should also know the basic purpose of records and enums.
Why You Might Want a Closed Hierarchy
An open class hierarchy allows any accessible class to extend a base class. An open interface allows any class to implement it. This flexibility is useful, but it can make code harder to reason about.
Suppose an API represents shapes. A method that handles Circle, Square, and Rectangle must also consider whether another implementation might appear later. A closed hierarchy is a type hierarchy whose permitted direct subtypes are known in advance.
Java sealed types provide this control. A sealed type documents its variants and lets the compiler check that code handles all of them. This is especially useful for domain models, protocols, and pattern-matching switch statements.
Declaring a Sealed Class or Interface
Use sealed on the base class or interface and list its direct permitted subtypes with permits:
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}This code requires Java 17 or later. The permits clause says that only the named types may directly implement Shape. Records are implicitly final, so they satisfy the rule for permitted subtypes.
A sealed class uses the same idea:
sealed abstract class Vehicle permits Car, Truck, Bike {}Each permitted direct subtype must explicitly choose how the hierarchy continues.
`final`, `sealed`, or `non-sealed`
Every direct permitted subtype must be final, sealed, or non-sealed.
| Modifier | Meaning |
|---|---|
| `final` | Ends inheritance at this subtype |
| `sealed` | Allows only its own listed subtypes |
| `non-sealed` | Reopens the hierarchy for unrestricted extension |
sealed abstract class Vehicle permits Car, Truck, Bike {}
final class Car extends Vehicle {}
sealed class Truck extends Vehicle permits PickupTruck {}
final class PickupTruck extends Truck {}
non-sealed class Bike extends Vehicle {}
class ElectricBike extends Bike {}Use final for a complete variant, sealed for another controlled layer, and non-sealed when an extension point is intentionally open.
Exercise
Which modifier should a permitted subclass use when no other class should extend it?
Show answer
final.