Quiz: Sealed Classes and Interfaces in Java

Total: 8 questions

1. 

What is a sealed class in Java and why does it exist?

A sealed class is a class or interface that lists its permitted subtypes itself, after the permits keyword. Any other class that uses extends or implements on it fails to compile. It has been a standard language feature since Java 17 (JEP 409), after previews in Java 15 and 16.

public sealed interface Shape permits Circle, Rect { }
public record Circle(double r) implements Shape { }
public record Rect(double w, double h) implements Shape { }

Before Java 17 there were only two options: everyone may extend the class, or nobody (final). Sealed adds the middle ground, a fixed set of variants: payment methods, a success/failure result, syntax tree nodes, domain events.

Sealed restricts inheritance, not use: the class can be public, instantiated and called from any package. The main payoff is an exhaustive switch without default: the compiler knows every variant and reports a missing one. sealed and permits are contextual keywords (a variable int permits is still legal), and non-sealed is the first hyphenated keyword in Java.

2. 

What rules apply to permits, and when can you leave it out?

permits comes after extends/implements: sealed class Transfer extends Payment permits Sepa, Swift. The link is two-way, and javac checks both sides:

  • a class is in permits but does not extend the parent: invalid permits clause (class B must extend sealed class);
  • a class extends the parent but is not listed: class is not allowed to extend sealed class: A (as it is not listed in its 'permits' clause);
  • a sealed class with no subclasses: sealed class must have subclasses.

The JLS sets three conditions: permits lists direct subclasses only (grandchildren go into the next level); each of them is accessible where the parent is declared; all are in the same module, or, without module-info.java, in the same package. Otherwise: class ... in unnamed module cannot extend a sealed class in a different package.

permits can be omitted if all subclasses are declared in the same source file: the compiler builds the list itself. As soon as a subclass moves to its own file, permits becomes mandatory.

3. 

Which modifier must a subclass of a sealed class have, and how do final, sealed and non-sealed differ?

Every permitted subclass must explicitly pick one of three modifiers; there is no default, and class B extends A gives sealed, non-sealed or final modifiers expected.

  • final: the branch ends, no further subclasses. The most common choice for leaf variants.
  • sealed: only the classes in its own permits may extend it; the variant splits into known sub-variants.
  • non-sealed: the branch is open to everyone again, including other packages and modules. For the compiler the hierarchy stays closed: any subclass of a non-sealed class counts as part of that branch.

non-sealed is only allowed on a direct subtype of a sealed type, otherwise non-sealed modifier not allowed here (class B does not have any sealed supertypes). The modifiers are mutually exclusive: sealed final gives illegal combination of modifiers: final and sealed. sealed abstract, however, is a normal combination: abstract says whether you can create an object, while final/sealed say who may extend the class.

4. 

How do sealed interfaces work, and how do records and enums fit into a sealed hierarchy?

An interface is sealed the same way as a class. Its permits may list both implementing classes and extending interfaces. An interface cannot be final, so a sub-interface can only be sealed or non-sealed: without a modifier you get sealed or non-sealed modifiers expected, with final you get illegal combination of modifiers: interface and final.

Records are implicitly final, so they go into permits without any modifier. "Sealed interface + records" is the standard way to express an algebraic data type: the interface fixes the set of variants, each record holds the data of one variant.

sealed interface Command permits Simple, Move { }
enum Simple implements Command { START, STOP }
record Move(int dx, int dy) implements Command { }

A plain enum is implicitly final as well and can be a permitted subtype; its constants work as case labels, and the switch stays exhaustive without default. An enum whose constants have bodies is made sealed by the compiler, but you cannot write sealed enum yourself: modifier sealed not allowed here. A sealed interface is often handier than a sealed class, because records and enums cannot extend classes.

5. 

Why does a switch over a sealed type need no default, and when is it still not exhaustive?

A switch with type patterns (JEP 441, standard since Java 21) must be exhaustive. For a regular type the only way is a default branch; for a sealed type it is enough to list every subtype. A missing variant gives the switch expression does not cover all possible input values (switch statement for a statement). That is why default "just in case" is a bad idea: with it the compiler cannot warn you about a new subtype.

  • A non-abstract sealed parent: if sealed class Transfer is not abstract, an instance of Transfer itself is possible, and without case Transfer t the switch is not exhaustive even when every subclass is listed.
  • A non-sealed branch is covered by one case, however many subclasses it has.
  • when: case Circle c when c.r() > 10 does not cover Circle entirely; an unguarded branch is needed too.
  • null is not part of the coverage: without case null you get NullPointerException.
  • Separate compilation: if a subtype appears after the switch was compiled, the JVM throws MatchException from an implicit default.

Branches often take a record apart right away, as in case Rect(double w, double h) -> w * h; record patterns are covered in detail in the records lesson.

6. 

How does a sealed interface affect casting and instanceof?

Normally a cast between an interface type and a non-final class always compiles, because some subclass might implement the interface. The mistake only shows up at run time as a ClassCastException.

With a sealed interface the compiler knows every implementor and can prove there is no overlap:

sealed interface Shape permits Circle { }
final class Circle implements Shape { }
class Square { }                         // not final

void m(Square sq, Shape s) {
    Shape x = (Shape) sq;                // incompatible types: Square cannot be converted to Shape
    boolean b = s instanceof Square;     // incompatible types: Shape cannot be converted to Square
}

A subclass of Square cannot implement Shape, because Shape permits only Circle. This way a closed hierarchy turns some run-time errors into compile-time errors.

7. 

Can an anonymous class, a local class or a lambda implement a sealed interface?

No. An anonymous or local class has no name that could go into permits, so it may not extend a sealed type, even in the same file:

  • new A() { }: anonymous classes must not extend sealed classes;
  • final class L implements A { } inside a method: local classes must not extend sealed classes.

A lambda is essentially an anonymous implementation too, so a sealed interface is not considered functional even with a single abstract method: Task t = () -> { }; gives Task is not a functional interface, and @FunctionalInterface on it gives Unexpected @FunctionalInterface annotation.

Nested classes (static and inner) are allowed: they have a name, such as Result.Ok, which can be listed in permits.

8. 

How can you tell through reflection that a class is sealed, and does the JVM enforce it?

Java 17 added two methods to java.lang.Class:

  • isSealed(): true if the type is sealed;
  • getPermittedSubclasses(): an array of the permitted subtypes, or null if the type is not sealed (for example, a non-sealed class).
System.out.println(Shape.class.isSealed());                              // true
System.out.println(Arrays.toString(Shape.class.getPermittedSubclasses()));
// [class Circle, class Rect, interface Polygon]

The JDK itself uses sealed types: java.lang.constant.ConstantDesc permits exactly nine implementations, among them String, Integer, Long, Float and Double.

Yes, the JVM enforces it: the list is stored in the PermittedSubclasses attribute of the class file and checked when classes are loaded. A "forbidden" subclass compiled separately fails to load with IncompatibleClassChangeError.

Page 1 of 1