Sealed Classes
- A sealed class is a class or interface which restricts which other classes or interfaces may extend it.
- Sealed classes and interfaces represent restricted class hierarchies that provide more control over an inheritance.
- All direct subclasses of a sealed class are known at compile time. No other subclasses may appear after a module with the sealed class is compiled.
- For example, third-party clients can't extend your sealed class in their code. Thus, each instance of a sealed class has a type from a
limited set that is known when this class is compiled.
Defining Sealed Classes
To seal a class, add the sealed modifier to its declaration. Then, after any extends and implements clauses, add the permits clause. This clause specifies the classes that may extend the sealed class.
For example, the following declaration of Shape specifies three permitted subclasses, Circle, Square, and Rectangle:
public sealed class Shape
permits Circle, Square, Rectangle {
}
Define the following three permitted subclasses, Circle, Square, and Rectangle, in the same module or in the same package as the sealed class:
public final class Circle extends Shape {
public float radius;
}
public non-sealed class Square extends Shape {
public double side;
}
public sealed class Rectangle extends Shape permits FilledRectangle {
public double length, width;
}
Rectangle has a further subclass, FilledRectangle:
public final class FilledRectangle extends Rectangle {
public int red, green, blue;
}
Constraints on Permitted Subclasses
They must be accessible by the sealed class at compile time.
For example, to compile Shape.java, the compiler must be able to
access all of the permitted classes of Shape: Circle.java,
Square.java, and Rectangle.java. In addition, because Rectangle is a
sealed class, the compiler also needs access to FilledRectangle.java.
They must directly extend the sealed class.
They must have exactly one of the following modifiers to describe how
it continues the sealing initiated by its superclass:
- final: Cannot be extended further
- sealed: Can only be extended by its permitted subclasses
- non-sealed: Can be extended by unknown subclasses; a sealed class
cannot prevent its permitted subclasses from doing this
For example, the permitted subclasses of Shape demonstrate each of
these three modifiers: Circle is final while Rectangle is sealed and
The Square is non-sealed.
They must be in the same module as the sealed class (if the sealed
class is in a named module) or in the same package (if the sealed
class is in the unnamed module, as in the Shape.java example).
For example, in the following declaration of com.example.graphics.Shape, its permitted subclasses are all in different packages. This example will compile only if Shape and all of its permitted subclasses are in the same-named module.
package com.example.graphics;
public sealed class Shape
permits com.example.polar.Circle,
com.example.quad.Rectangle,
com.example.quad.simple.Square { }