A sealed class or interface lists exactly which classes may extend or implement it, using the permits clause. This gives you a closed, known set of subtypes, which is useful for modelling domain concepts and lets the compiler check that a switch covers every case.
Key Points: • Declare it with sealed and permits: sealed interface Shape permits Circle, Square, Rectangle. • Every permitted subclass must be final, sealed (restricting further), or non-sealed (open again). • Permitted subclasses must be in the same module, or in the same package if you don't use modules. If they are in the same file, permits can be omitted. • Records are implicitly final, so they pair naturally with sealed interfaces. • It sits between final (no subclasses) and a normal class (anyone can extend it).
Code Example:
public class SealedDemo {
sealed interface Payment permits Card, Upi, Cash {}
record Card(String number) implements Payment {}
record Upi(String vpa) implements Payment {}
record Cash(double amount) implements Payment {}
// final class Crypto implements Payment {} // compile error: not permitted
static String describe(Payment p) {
return switch (p) { // no default needed: all cases covered
case Card c -> "Card ending " + c.number().substring(c.number().length() - 4);
case Upi u -> "UPI " + u.vpa();
case Cash c -> "Cash Rs " + c.amount();
};
}
public static void main(String[] args) {
System.out.println(describe(new Card("4111111111111111")));
System.out.println(describe(new Upi("asha@okbank")));
System.out.println(describe(new Cash(250)));
}
}Output:
Card ending 1111 UPI asha@okbank Cash Rs 250.0
Good to Know: Explain the real benefit: if someone later adds a new permitted type, every switch over the sealed type stops compiling until it handles the new case. That turns a runtime bug ("we forgot to handle crypto payments") into a compile-time error.
Interview Tip: A concise interview answer is:
"A sealed class or interface uses permits to list exactly which classes may extend it, and each permitted class must be final, sealed or non-sealed. It gives a closed set of subtypes, so a switch over it can be checked for completeness by the compiler."
Previous question: What is the difference between a record, a regular class and a Lombok @Data class?
Next question: What are switch expressions in Java, and how are they different from the old switch statement?