Java / Java 21 Interview Questions
What are sealed classes and interfaces in Java and why are they important for pattern matching?
Sealed classes (JEP 409, finalised in Java 17, heavily used with Java 21 pattern matching) restrict which classes can extend or implement them. You declare the permitted subtypes explicitly in a permits clause, giving the compiler a closed world of possibilities.
// Sealed interface — only these three can implement it
public sealed interface Expr
permits Num, Add, Mul {
}
public record Num(int value) implements Expr {}
public record Add(Expr l, Expr r) implements Expr {}
public record Mul(Expr l, Expr r) implements Expr {}
// Evaluator — exhaustive switch, no default needed
static int eval(Expr e) {
return switch (e) {
case Num(int v) -> v;
case Add(Expr l, Expr r) -> eval(l) + eval(r);
case Mul(Expr l, Expr r) -> eval(l) * eval(r);
};
}
// Usage: (2 + 3) * 4 = 20
Expr expr = new Mul(new Add(new Num(2), new Num(3)), new Num(4));
System.out.println(eval(expr)); // 20Permitted subclasses must be in the same package (or module). Each permitted class must be one of: final (no further extension), sealed (extends the hierarchy with its own permits), or non-sealed (reopens the hierarchy for any extension).
| Modifier | Meaning |
|---|---|
| final | No further subclassing allowed |
| sealed | Can be extended, but only by its own permits clause |
| non-sealed | Opens the type back up — any class can extend it |
The key synergy with Java 21: because the compiler knows the complete set of sealed subtypes, a switch over a sealed type can be checked for exhaustiveness at compile time. If you add a new subtype to the sealed hierarchy, every exhaustive switch in the codebase becomes a compile error until it is updated.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
