1. What is a Sealed Class?
A sealed class is a class that restricts which other classes or interfaces can extend or implement it. It allows you to control the inheritance hierarchy more strictly than abstract
classes.
Think of it like saying:
“Only these specific classes are allowed to inherit from me.”
2. Why Use Sealed Classes?
- Control over inheritance – prevents unwanted subclasses.
- Better maintainability – you know all possible subclasses at compile-time.
- Pattern matching support – works well with the
switch
expression introduced in Java 17+.
3. Syntax
A sealed class uses the keyword sealed
and a permits
clause that lists allowed subclasses:
// Sealed class
public sealed class Shape permits Circle, Rectangle, Square {
// common behavior
abstract double area();
}
// Permitted subclass 1
public final class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
// Permitted subclass 2
public final class Rectangle extends Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
4. Rules for Sealed Classes
- Must explicitly list subclasses using
permits
. - Subclasses must be either:
final
→ cannot be extended further.non-sealed
→ allows further extension.sealed
→ further restricts its own subclasses.
- Can be abstract or concrete.
5. Subclass Types
Type | Meaning |
---|---|
final | Cannot be extended further. |
sealed | Can only be extended by a defined set of classes (new permits list). |
non-sealed | Can be freely extended, removes the sealed restriction. |
Example of non-sealed
:
public non-sealed class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
double area() {
return side * side;
}
}
6. When to Use
- Algebraic data types (like in functional programming).
- Pattern matching in
switch
expressions. - Restrict inheritance in libraries or frameworks.
✅ Key Points
- Sealed classes are introduced in Java 17.
- They give compile-time control over class hierarchies.
- They improve readability, safety, and maintainability.