Java 17 (LTS) · Topic 1 of 2
Sealed classes
Definition​
A sealed class or interface lists exactly which classes may extend it, using permits. The compiler then knows every possible subtype, so a switch over it is checked for completeness without a default.
Example code​
A closed set of payment types
sealed interface Payment permits Card, Upi, Cash { }
record Card(String number) implements Payment { }
record Upi(String id) implements Payment { }
record Cash() implements Payment { }
class Demo {
static String describe(Payment payment) {
return switch (payment) { // no default: the compiler knows all cases
case Card c -> "Card ending " + c.number().substring(c.number().length() - 4);
case Upi u -> "UPI " + u.id();
case Cash c -> "Cash";
};
}
public static void main(String[] args) {
System.out.println(describe(new Card("1234567812345678")));
System.out.println(describe(new Upi("asha@bank")));
System.out.println(describe(new Cash()));
// adding a new Payment type makes describe() fail to compile until you handle it
}
}
// Output:
// Card ending 5678
// UPI asha@bank
// Cash
Finished this page? Track your progress (saved only in your browser).