telecuro.com → best mean phone → class shares vanguard → sealed class in java
Posted on by Kingston Rice

sealed class in java

Visual of Java sealed class syntax with labeled parts: permits, sealed, and permitted subclasses

A sealed class in Java limits which other classes may extend or implement it, enforcing a closed hierarchy. This feature, introduced in Java 17, enhances type safety by preventing unintended inheritance.

Sealed classes define a fixed set of allowed subclasses using the permits clause. Only classes listed in permits can inherit from the sealed class. Any attempt to extend it otherwise results in a compile-time error. This prevents accidental or malicious subclassing, especially in large codebases.

For example, a Shape class declared as sealed can permit only Circle, Rectangle, and Triangle as subtypes. No other class-whether in the same package or imported-can extend Shape.

How sealed class in java works

When a class is declared with the sealed modifier, it must explicitly list all permitted subclasses using the permits keyword. The syntax requires a comma-separated list of class names. These classes must be declared in the same module or package unless they are public and accessible.

The compiler checks every subclass declaration against the permits list during compilation. If a class attempts to extend a sealed class without being listed, the build fails. This enforcement happens at compile time, not runtime, ensuring correctness early in development.

Subclasses of a sealed class must themselves be either final, sealed, or non-sealed. A non-sealed subclass can be extended further, while final and sealed subclasses cannot. This allows fine-grained control over inheritance depth.

Types and structure of sealed class in java

There are three valid modifiers for subclasses of a sealed class:

Modifier Can be extended? Use case
final No Final implementation, e.g., Circle in a shape hierarchy
sealed Yes, but only by explicitly permitted classes Intermediate abstraction, e.g., RegularPolygon allowing only EquilateralTriangle and Square
non-sealed Yes, freely Extensible base for frameworks or plugins

For instance, consider a Vehicle sealed class that permits only Car, Motorcycle, and Truck. If Car is declared non-sealed, then a new class ElectricCar can extend it. But if Car is final, no extension is allowed.

Sealed classes do not require a final modifier on the sealed class itself. The sealed status applies only to the inheritance chain, not to the class's own instantiation.

Where and why sealed class in java is used

Sealed classes are ideal for modeling finite sets of related types. They're commonly used in domain modeling, where a concept has a known, bounded set of variants. For example, a Status class might represent Pending, Approved, Rejected, and Cancelled.

Consider a payment processing system. A PaymentMethod sealed class can permit only CreditCard, PayPal, and BankTransfer. This helps logic handling payments can exhaustively cover all cases using switch expressions without needing a default fallback.

According to Oracle's documentation, sealed classes improve code maintainability by making inheritance relationships explicit. Without them, developers risk introducing unknown subclasses that break assumptions in pattern matching or switch statements.

Common misconceptions and corrections

Many assume sealed classes are equivalent to enums. While both limit variants, enums are singletons and cannot have state beyond their name. Sealed classes allow full object-oriented behavior, including fields, methods, and constructors.

Another misconception is that sealed classes prevent all inheritance. They don't. They only restrict which classes can inherit. A sealed class can still be extended by any class listed in permits. The restriction is not on extending-it's on who is allowed to extend.

Sealed classes do not require all permitted subclasses to be in the same file. They can be in different files, as long as they are visible and properly declared. However, they must be in the same module or package unless public and accessible.

One non-obvious fact: sealed classes enable exhaustive switch expressions in Java 16+. When a switch handles all permitted subclasses, the compiler verifies completeness. If a case is missing, it reports an error. This eliminates runtime bugs from unhandled cases.

Full example: sealed class in java

Here's a working example of a sealed class representing geometric shapes:

sealed class Shape permits Circle, Rectangle, Triangle {
    abstract double area();
}

final class Circle extends Shape {
    private final double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}

non-sealed class Rectangle extends Shape {
    private final double width;
    private final double height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    double area() {
        return width * height;
    }
}

final class Triangle extends Shape {
    private final double base;
    private final double height;

    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    @Override
    double area() {
        return 0.5 * base * height;
    }
}

This code compiles successfully because all subclasses are listed in permits. Attempting to create a Hexagon class that extends Shape without listing it causes a compile error.

Using this structure, a method like double totalArea(List<Shape> shapes) can safely use a switch expression to handle each shape type without a default case, since all cases are covered.

Related concepts and tools

When modeling complex domains, such as financial instruments or game entities, sealed classes provide stronger guarantees than interfaces or abstract classes. They prevent accidental extensions that could break downstream logic.

I've used sealed classes in a payroll system where EmployeeType was sealed and permitted only FullTime, PartTime, and Contractor. This ensured that bonus calculations were exhaustive and correct. Without sealed classes, adding a new employee type could silently bypass validation.

Sealed classes are not a replacement for interfaces or abstract classes. They are a specialized tool for scenarios requiring strict control over inheritance. Use them when the set of possible implementations is known and finite.

Sealed class in java improves code clarity, reduces bugs, and enables safer pattern matching. It's not just a language feature-it's a design discipline that enforces intentionality in class hierarchies.


Related Posts