Java Sealed Classes (Java 17–21 Features)

Introduction

However, unrestricted inheritance can sometimes make applications difficult to manage because any class can extend a base class unless it is declared as final. This can lead to unexpected behavior, security issues, and code that is harder to maintain.

Before Java 17, developers had only two options:

  • Use a normal class, which any class could extend.
  • Use a final class, which no class could extend.

There was no middle ground where developers could specify exactly which classes were allowed to inherit from a parent class.

To address this limitation, Java introduced Sealed Classes as a preview feature in Java 15, continued the preview in Java 16, and officially made them a standard feature in Java 17. Sealed classes give developers precise control over inheritance by explicitly declaring which classes are permitted to extend or implement them.

What are Java Sealed Classes?

A Sealed Class is a special type of class that restricts which other classes or interfaces can extend or implement it.

Unlike a regular class, where inheritance is open to all subclasses, a sealed class explicitly lists its permitted subclasses using the permits keyword.

This provides developers with complete control over the inheritance hierarchy.

Why Were Sealed Classes Introduced?

Consider a payment system:


Payment
├── CreditCard
├── DebitCard
├── UPI
├── NetBanking

Suppose only these four payment types should ever exist.

Without sealed classes, someone could write:


class CryptoPayment extends Payment {
}

This might violate the intended design.

With a sealed class, Java prevents unauthorized subclasses from being created.

Syntax of Sealed Classes

public sealed class ClassName


   permits SubClass1, SubClass2, SubClass3 {
}

Example:


public sealed class Vehicle
   permits Car, Bike, Truck {
}

Only Car, Bike, and Truck can extend Vehicle.

First Example


public sealed class Shape
       permits Circle, Rectangle {
}
public final class Circle extends Shape {
}
public final class Rectangle extends Shape {

}

Valid hierarchy:


Shape
├── Circle
└── Rectangle

Invalid Example

Attempting to create another subclass:


public class Triangle extends Shape {
}

Compilation Error:

Class is not allowed to extend sealed class Shape

The permits Keyword

The permits keyword specifies the classes allowed to inherit from the sealed class.

Example:


public sealed class Animal
   permits Dog, Cat {
}

Only:

  • Dog
  • Cat

can extend Animal.

Rules for Sealed Classes

Java imposes several rules on sealed classes.

Rule 1: Use the sealed Keyword


public sealed class Animal
   permits Dog, Cat {
}

Rule 2: Declare Permitted Classes

Every permitted subclass must be listed.

permits Dog, Cat

Rule 3: Permitted Classes Must Extend the Parent


public final class Dog extends Animal {
}

Rule 4: Permitted Classes Must Be Nearby

The permitted subclasses must be located in:

  • the same module, or
  • the same package (if using the unnamed module).

Subclass Modifiers

Every permitted subclass must explicitly choose one of three modifiers:

  • final
  • sealed
  • non-sealed

This rule ensures that the inheritance hierarchy remains explicit.

Using final

A final subclass cannot be extended further.


public final class Car extends Vehicle {
}
Hierarchy:
Vehicle
└── Car

No further subclasses are allowed.

Using sealed

A subclass can itself be sealed.


public sealed class Animal
   permits Mammal {
}
public sealed class Mammal
   extends Animal
   permits Dog, Cat {
}

Hierarchy:


Animal
└── Mammal
   ├── Dog
   └── Cat

Using non-sealed

A subclass may reopen inheritance.


public non-sealed class Bike
   extends Vehicle {
}
Now anyone can extend Bike.

Example:


public class SportsBike extends Bike {
}

Real-Life Example: Banking System

Imagine a banking application.

Only three account types should exist.


public sealed class BankAccount
   permits SavingsAccount,
           CurrentAccount,
          LoanAccount {
}
public final class SavingsAccount
      extends BankAccount {
}
public final class CurrentAccount
       extends BankAccount {
}
public final class LoanAccount
       extends BankAccount {
}

Now developers cannot accidentally create:


class CryptoAccount extends BankAccount {
}

This improves security and design consistency.

Sealed Interfaces

Interfaces can also be sealed.


public sealed interface Payment
       permits CardPayment,
               UPIPayment {
}
public final class CardPayment
       implements Payment {
}
public final class UPIPayment
       implements Payment {
}

Sealed Classes with Pattern Matching

One of the biggest advantages of sealed classes is better compatibility with pattern matching.

Example:


public sealed interface Shape
   permits Circle, Rectangle {
}

When using switch pattern matching, the compiler knows all possible subclasses.

This enables exhaustive checking and reduces bugs because every permitted subtype can be handled explicitly.

Advantages of Sealed Classes

1. Controlled Inheritance

Only approved subclasses are allowed.

2. Better API Design

Framework authors can prevent unintended inheritance.

3. Improved Security

Unauthorized subclasses cannot modify application behavior.

4. Better Compiler Checks

The compiler understands every permitted subclass.

5. Cleaner Domain Models

Business rules become easier to enforce.

6. Better Integration with Pattern Matching

Future Java features work exceptionally well with sealed hierarchies.

Limitations of Sealed Classes

Although sealed classes are powerful, they have some restrictions.

Cannot Forget Subclass Modifier

Every permitted subclass must be:

  • final
  • sealed
  • non-sealed

Cannot Permit Unknown Classes

Every subclass must appear in the permits list.

Cannot Ignore Package Rules

Permitted classes must be located in the same package or module.

More Suitable for Fixed Hierarchies

If your application requires unlimited inheritance, sealed classes are not the right choice.

Sealed Classes vs Final Classes

Feature Sealed Class Final Class
Can be inherited Yes No
Controls subclasses Yes No
Uses permits Yes No
Supports hierarchy Yes No
Best for Controlled inheritance No inheritance

Sealed Classes vs Regular Classes

Feature Regular Class Sealed Class
Controlled hierarchy Yes No
Compiler enforcement Limited Strong
API safety Moderate High
Domain modeling Flexible Explicit

Common Mistakes

1. Forgetting the permits Clause

Wrong:


public sealed class Vehicle {
}

The compiler expects the permitted subclasses to be declared (unless they are inferred in the same source file where allowed).

2. Forgetting the Subclass Modifier

Wrong:


public class Car extends Vehicle {
}

Correct:


public final class Car extends Vehicle {
}

3. Extending Without Permission

Wrong:


class Bus extends Vehicle {
}

Compilation fails because Bus is not listed in the permits clause.

4. Using Sealed Classes for Flexible Designs

If many unknown subclasses may be created by external developers, a regular abstract class or interface is often a better choice.

Best Practices

  • Use sealed classes for fixed domain models.
  • Prefer final subclasses unless further inheritance is required.
  • Use non-sealed only when reopening inheritance is intentional.
  • Keep the hierarchy simple and well documented.
  • Combine sealed classes with pattern matching and switch expressions where appropriate.
  • Use meaningful class names that clearly represent the domain.

Conclusion

Java Sealed Classes are one of the most significant language enhancements introduced in Java 17. They fill the gap between completely open inheritance and completely closed (final) classes by allowing developers to define exactly which classes can participate in an inheritance hierarchy.

This feature improves code safety, maintainability, and readability while making APIs and domain models more robust. Sealed classes are especially valuable in applications where the set of valid subclasses is known in advance, such as banking systems, payment gateways, compiler design, and business domain models.

Related Java Tutorials