Sealed classes are a modern object-oriented feature that restricts which classes are allowed to extend or implement them. They provide stronger control over class hierarchies while keeping code readable, predictable, and secure.
The class below allows only CreditCard and PayPal.
Click a subclass button to see if the compiler accepts it.
A sealed class explicitly declares which classes are permitted to extend it using the permits keyword. Subclasses must declare themselves as final, sealed, or non-sealed.
// Sealed base class restricting inheritance
public sealed class Shape permits Circle, Rectangle {
}
// Allowed subclass marked as final
public final class Circle extends Shape {
}
// Another permitted subclass
public final class Rectangle extends Shape {
}
The Shape class controls its hierarchy by allowing only Circle and Rectangle to extend it. Any other class attempting to inherit from Shape will cause a compile-time error.
Vehicle with permitted subclassesnon-sealed subclasses