What is a sealed class, introduced in Java 15, and its usage?

A sealed class is a special type of class introduced in Java 15 that allows developers to explicitly control which classes or interfaces can inherit from it. By restricting inheritance to a predefined set of subclasses, sealed classes provide better control over class hierarchies, improve maintainability, and enhance type safety.

Key Points: • A sealed class restricts inheritance to only the classes listed in its permits clause. • Permitted subclasses must be declared as final, sealed, or non-sealed. • Sealed classes are useful for modeling fixed hierarchies where all possible subtypes are known in advance.

Example: Consider a payment system where only CreditCardPayment, UpiPayment, and NetBankingPayment should be valid payment types. A sealed class ensures that no other unauthorized payment implementation can be created outside the defined hierarchy.

Code Example: sealed class Payment permits CreditCardPayment,

                UpiPayment,
                NetBankingPayment {
}

final class CreditCardPayment
        extends Payment {
}

final class UpiPayment
        extends Payment {
}

final class NetBankingPayment
        extends Payment {
}

public class Main {

    public static void main(String[] args) {

        Payment payment =
                new UpiPayment();

        System.out.println(
                payment.getClass().getSimpleName());
    }
}

Interview Tip: A concise interview answer is: A sealed class restricts which classes can extend or implement it by explicitly defining permitted subclasses. It helps create controlled class hierarchies, improves type safety, and is particularly useful when all valid subtypes are known in advance.