Sub topic 3
final, sealed or non-sealed: what each subclass must choose
This chapter assumes you know Java inheritance, interfaces, the final keyword, and the basics of records and enums. It also assumes you have read the previous chapter, where a sealed type lists its permitted subclasses. Here the focus moves to the other side of that relationship: what each permitted subclass has to declare about itself. The examples need Java 17 or later, and the switch example needs Java 21.
The rule: every direct subclass must pick one
A sealed type controls who may extend it. That control would be pointless if a permitted subclass could then be extended by anyone. So the language adds a second rule. Every class that directly extends a sealed class, or directly implements a sealed interface, must declare exactly one of three modifiers:
final: no class may extend this one.sealed: only the classes in its ownpermitsclause may extend it.non-sealed: any class may extend it. The restriction ends here.
If you write none of them, the compiler rejects the class. The same applies if you write more than one. The rule applies to direct subclasses only. A class that extends a non-sealed class is an ordinary class and has no obligation.
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 {}Each of the three direct subclasses of Vehicle makes a different choice:
Carends the hierarchy.Trucknarrows it further, so it must list its own subclasses.PickupTruckthen has to choose a modifier too, and it picksfinal.Bikereopens the hierarchy.ElectricBikeneeds no modifier at all.
The diagram shows how the restriction flows down the tree.
What each modifier means for the compiler
final
A final permitted subclass is a leaf. The compiler knows its full set of instances is just itself and nothing below it. This is the choice you want most of the time, because it keeps the hierarchy fully known. It is also what makes exhaustive switch expressions possible, which is covered in a later chapter.
sealed
A sealed permitted subclass is a branch with its own closed list. The permits clause on Truck names PickupTruck, and nothing else may extend Truck. You use this when a category has sub-categories that you also want to control. The compiler can still enumerate every leaf by following the chain of sealed types, so exhaustiveness checking still works.
Two details trip people up:
- A
sealedclass must have at least one permitted subclass. Asealedclass with an empty list is a compile-time error. - Every class named in a
permitsclause must actually extend the class that names it. Listing an unrelated class is an error.
non-sealed
non-sealed deliberately gives up control for one branch. The name is the only Java keyword written with a hyphen. Any class, in any package where the class is accessible, may extend a non-sealed class.
The cost is that the compiler no longer knows every subtype. A switch over Vehicle still sees Bike as a covered case, because Bike itself is permitted. It does not matter how many ElectricBike-style subclasses exist, since each one is a Bike. The hierarchy is still closed at the level of Vehicle's direct subclasses, and only the interior of the Bike branch is open.
Use non-sealed when you want a closed top level and an extension point underneath it. A typical case is a library that defines a fixed set of categories but lets users create their own specializations in one of them.
Comparing the three
| Modifier | Can be extended? | Needs a `permits` list? | Effect on exhaustiveness |
|---|---|---|---|
| `final` | No | No | Leaf, fully known |
| `sealed` | Only by its permitted subclasses | Yes, unless they share the compilation unit | Known by following the chain |
| `non-sealed` | By any class | No | Counts as one case. Its subtypes are covered by it |
How the choice shows up in a switch
The following example uses the hierarchy above. Because every direct subclass of Vehicle is either final, sealed or non-sealed, the compiler can check that a switch covers all of them.
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 {}
public class VehicleDemo {
static String describe(Vehicle v) {
return switch (v) {
case Car c -> "car";
case Truck t -> "truck";
case Bike b -> "bike";
};
}
public static void main(String[] args) {
System.out.println(describe(new Car()));
System.out.println(describe(new PickupTruck()));
System.out.println(describe(new ElectricBike()));
}
}This prints car, truck and bike. There is no default branch. A PickupTruck matches case Truck t because it is a Truck. An ElectricBike matches case Bike b for the same reason. If you remove the Truck case, the code stops compiling, and the error message says the switch expression does not cover all possible input values.
If you later add a fourth permitted subclass, every switch like this one fails to compile until you handle the new case. That is the main benefit of choosing final and sealed over non-sealed.
Common errors
The compiler messages differ between versions, but the causes are stable.
- Missing modifier. A permitted subclass declared as
class Car extends Vehicle {}is rejected. The fix is to addfinal,sealedornon-sealed. - Two modifiers.
final non-sealed class Bikeis rejected, because the two contradict each other. The same goes forfinal sealed. - Sealed without subclasses.
sealed class Truck extends Vehicle {}with nopermitsclause and no subclass in the same file is rejected. - Not named in
permits. IfVehiclelistsCar, Truckand you writefinal class Bike extends Vehicle {}, thenBikeis rejected, even if it carries a valid modifier. - Modifier on a non-permitted level. Putting
non-sealedon a class whose parent is not sealed is an error. The modifier only makes sense directly below a sealed type.
The last one is worth remembering. non-sealed is not a general-purpose keyword. It means "this is a permitted subclass of a sealed type, and I opt out of the restriction."
Records and enums choose for you
Records are implicitly final, so a record can implement a sealed interface without writing any modifier. This is why the earlier Shape example works:
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 {}An enum is also either implicitly final or, when it has constants with bodies, implicitly sealed. Both satisfy the rule without extra keywords. The next chapters return to records and enums in detail. For now, remember that for those two kinds of type the choice has already been made.
Choosing between the three
Ask these questions in order.
- Should this subclass ever have its own subclasses? If not, use
final. This is the default choice. - If yes, do you want to know every one of them at compile time? If so, use
sealedand list them. - If you cannot or do not want to list them, use
non-sealed, and accept that switches cannot see below that level.
A useful habit is to start with final everywhere and loosen a single branch only when a real requirement appears. Moving from final to sealed or non-sealed is easy later. Going the other way can break code that already extends the class.
Exercise
A sealed interface Event permits Click, Key and Custom. You want Click and Key to be leaves, and you want library users to be able to create their own subclasses of Custom. What modifier does each of the three classes need, and what happens to a switch over Event when a user defines class MyCustom extends Custom {}?
Show answer
Click and Key are final, and Custom is non-sealed. The switch is unaffected, because MyCustom is a Custom and is covered by case Custom c. The switch stays exhaustive with three cases and needs no default.
Exercise
This code does not compile. Give two different fixes. sealed class Base permits Child {} class Child extends Base {}
Show answer
Child has no modifier. Add final to end the hierarchy (final class Child extends Base {}), or add non-sealed to allow further subclasses (non-sealed class Child extends Base {}). A third option is sealed class Child extends Base permits GrandChild {} together with a permitted GrandChild.