☕ Java Advanced

What are sealed classes in Java?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized Java deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

Sealed classes and interfaces (Java 17) restrict which other classes can extend or implement them. public sealed class Shape permits Circle, Rectangle, Triangle { } — only the explicitly listed classes are allowed to be subclasses. Each permitted subclass must be declared final, sealed itself, or non-sealed (re-opens the hierarchy). Sealed classes enable exhaustive pattern matching in switch expressions — the compiler can verify all subtypes are handled without a default case. This brings algebraic data type (sum type) modeling to Java, similar to Kotlin sealed classes. They are particularly useful for modeling domain states, results, and discriminated unions.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.