Sub topic 17
Sealed Classes and Interfaces
What Problem Does Sealing Solve?
Normally, any class can implement your interface or extend your abstract class. Sometimes you don't want that. Say your program only knows about two kinds of vehicle: cars and trucks. If a stranger's code adds a Boat, your code may not know how to handle it.
A sealed type is a class or interface that lists exactly which classes may extend or implement it. No other class is allowed. Sealed types became a standard part of Java in Java 17.
The `permits` Clause
You mark a type with the word sealed. Then you add a permits clause, which is a list of the only classes allowed to inherit from it.
Each permitted class must also say how it continues the family. It must use one of three words:
| Modifier | Meaning |
|---|---|
| `final` | No class can extend this class. |
| `sealed` | This class has its own `permits` list. |
| `non-sealed` | Any class may extend this class again. |
A Worked Example
Save this as Main.java and run it with Java 17 or later.
sealed interface Vehicle permits Car, Truck {}
final class Car implements Vehicle {}
final class Truck implements Vehicle {}
public class Main {
static String describe(Vehicle v) {
if (v instanceof Car) {
return "car";
} else if (v instanceof Truck) {
return "truck";
}
throw new IllegalStateException();
}
public static void main(String[] args) {
System.out.println(describe(new Car())); // prints: car
}
}Here is what each part does:
sealed interface Vehicle permits Car, Trucksays onlyCarandTruckmay implementVehicle.- Both classes are
final, so the family ends there. - The
describemethod checks every allowed kind. You know the list is complete because nothing else can be aVehicle.
If you add class Boat implements Vehicle {}, the compiler reports an error, because Boat is not in the permits list.
Sealed Abstract Classes
Abstract classes can be sealed too. The rules are the same.
sealed abstract class Shape permits Circle, Square {}
final class Circle extends Shape {}
non-sealed class Square extends Shape {}
class BigSquare extends Square {} // allowed, because Square is non-sealed
public class Main {
public static void main(String[] args) {
Shape s = new BigSquare();
System.out.println(s instanceof Square); // prints: true
}
}Square is non-sealed, so BigSquare is allowed to extend it.
Exercises
Exercise
You add final class Bike implements Vehicle {} to the first example without changing anything else. What happens, and how do you fix it?
Show answer
The code will not compile, because Bike is not listed in Vehicle's permits clause. To fix it, change the first line to sealed interface Vehicle permits Car, Truck, Bike {}.
Exercise
A permitted class is declared as just class Truck implements Vehicle {}, with no modifier. Is that allowed?
Show answer
No. Every permitted class must be declared final, sealed, or non-sealed. Adding one of those words, such as final, fixes the error.