Tech Interview RoomStudy guides

Java 17

Java 17: Sealed classes and pattern matching for instanceof. Compare instanceof casts, polymorphism, the visitor pattern and sealed types.

Advanced · 2 min read · Lesson 6 of 8 in Java 17

Problem

Shipments come in three kinds: Standard(weightKg), Express(weightKg, distanceKm) and Pickup. Compute the shipping fee, and later add other operations (label text, estimated days) without breaking anything.

Approach 1: instanceof and casts (Java 8)

Works, but each branch repeats the type in a cast, the compiler cannot tell you when a new type is not handled, and the else silently swallows mistakes.

java
class FeeInstanceofJava8 {
    static double fee(Object shipment) {
        if (shipment instanceof StdShipment) {
            StdShipment s = (StdShipment) shipment;
            return 40 + 10 * s.weightKg();
        } else if (shipment instanceof ExpShipment) {
            ExpShipment e = (ExpShipment) shipment;
            return 100 + 15 * e.weightKg() + 0.5 * e.distanceKm();
        } else if (shipment instanceof PickupShipment) {
            return 0;
        }
        throw new IllegalArgumentException("Unknown shipment " + shipment);
    }
}

Approach 2: Polymorphism (classic OOP)

Each type implements fee(). Adding a new type is easy (one class), but adding a new operation means editing every class, and the logic spreads across files.

java
interface PricedShipment { double fee(); }

record PricedStandard(double weightKg) implements PricedShipment {
    public double fee() { return 40 + 10 * weightKg; }
}
record PricedExpress(double weightKg, double distanceKm) implements PricedShipment {
    public double fee() { return 100 + 15 * weightKg + 0.5 * distanceKm; }
}
record PricedPickup() implements PricedShipment {
    public double fee() { return 0; }
}

Approach 3: Visitor pattern

Lets you add operations without touching the types and the compiler checks every type is handled, at the cost of a lot of ceremony (accept/visit double dispatch).

java
interface ShipmentVisitor<R> {
    R visitStandard(VStandard s);
    R visitExpress(VExpress e);
    R visitPickup(VPickup p);
}
interface VShipment { <R> R accept(ShipmentVisitor<R> v); }
record VStandard(double weightKg) implements VShipment { public <R> R accept(ShipmentVisitor<R> v) { return v.visitStandard(this); } }
record VExpress(double weightKg, double distanceKm) implements VShipment { public <R> R accept(ShipmentVisitor<R> v) { return v.visitExpress(this); } }
record VPickup() implements VShipment { public <R> R accept(ShipmentVisitor<R> v) { return v.visitPickup(this); } }

class FeeVisitor implements ShipmentVisitor<Double> {
    public Double visitStandard(VStandard s) { return 40 + 10 * s.weightKg(); }
    public Double visitExpress(VExpress e) { return 100 + 15 * e.weightKg() + 0.5 * e.distanceKm(); }
    public Double visitPickup(VPickup p) { return 0.0; }
}

Approach 4: Sealed interface + records + pattern matching for instanceof (Java 17)

sealed ... permits fixes the set of subtypes, so the domain is closed and documented in one place. instanceof Express e tests and binds in one step, with no cast. Data and operations stay separate, like the visitor, with far less code.

java
sealed interface Shipment permits StdShipment, ExpShipment, PickupShipment {}
record StdShipment(double weightKg) implements Shipment {}
record ExpShipment(double weightKg, double distanceKm) implements Shipment {}
record PickupShipment() implements Shipment {}

class FeeSealed {
    static double fee(Shipment s) {
        if (s instanceof StdShipment st) return 40 + 10 * st.weightKg();
        if (s instanceof ExpShipment ex && ex.distanceKm() > 1000) return 100 + 15 * ex.weightKg() + 400;   // pattern + condition
        if (s instanceof ExpShipment ex) return 100 + 15 * ex.weightKg() + 0.5 * ex.distanceKm();
        if (s instanceof PickupShipment) return 0;
        throw new AssertionError("unreachable for a sealed hierarchy");
    }
}

class ShipmentDemo {
    public static void main(String[] args) {
        System.out.println(FeeInstanceofJava8.fee(new StdShipment(2)) + " " + FeeSealed.fee(new StdShipment(2)));   // 60.0 60.0
        System.out.println(FeeSealed.fee(new ExpShipment(1, 200)) + " " + new PricedExpress(1, 200).fee());         // 215.0 215.0
        System.out.println(new VExpress(1, 200).accept(new FeeVisitor()));                                         // 215.0
        System.out.println(FeeSealed.fee(new ExpShipment(1, 2000)) + " " + FeeSealed.fee(new PickupShipment()));  // 515.0 0.0
    }
}

Feasible → optimal

  • instanceof + casts: feasible, unsafe when the hierarchy grows.
  • Polymorphism: optimal when behaviour naturally belongs to the type and new types are added often.
  • Visitor: type-safe operations over a fixed hierarchy, but verbose.
  • Sealed + patterns: the modern optimum for closed data models where you add operations often (pricing, rendering, validation). In Java 21 a pattern switch over the sealed type is checked for exhaustiveness by the compiler, removing the final throw.

Follow-up questions interviewers ask

Try answering each one before you open it.

What do sealed, final and non-sealed mean for the permitted subclasses?

Every permitted subclass must declare how it continues the hierarchy: final (no further subclasses; records are implicitly final), sealed (its own restricted list), or non-sealed (open again for anyone to extend). Permitted subclasses must be in the same module, or the same package in the unnamed module, and can be omitted from permits if they are in the same source file.

What is the "expression problem" and how do sealed types relate to it?

It is the trade-off between adding new types and adding new operations. OOP polymorphism makes new types cheap and new operations expensive; functional/data-oriented designs (sealed types plus pattern matching) make new operations cheap and new types expensive, but the compiler then points to every switch that must handle the new type. Pick the style that matches how your domain changes.