Sealed Classes in Java 17
An Introduction
What are Sealed Classes?
Sealed classes are a feature introduced in Java 16 (as a preview feature) and finalized in Java 17.
Sealed classes allow developers to restrict the inheritance hierarchy of a class or interface. In other words, they provide more control over how a class can be extended or implemented.
Code Example for a Sealed class
Take a Shape
class, which can be extended by Circle
, Square
, or Triangle
classes. With Sealed Classes, we can specify that only these three classes can inherit from Shape
, and no other class can extend it.
Check syntax below:
public sealed class Shape permits Circle, Square, Triangle {
// Class definition
}
Above, we have defined a sealed class, Shape, which allows only Circle, Square, and Triangle to extend it.
1. Defining a sealed class
public sealed interface Vehicle permits Car, Bike {
void start();
}
In this example, we have defined a sealed interface calledVehicle
which permits only Car
and Bike
classes to implement it. The interface defines a single method called start
().