Sealed Interface and Pattern Matching
In Java, sealed interfaces are a powerful feature introduced to provide fine-grained control over inheritance. Here’s an example to illustrate how they work:
public sealed interface Shape permits Circle, Rectangle {}
public non-sealed class Circle implements Shape {}
public final class Rectangle implements Shape {}
Understanding Sealed Interfaces
The Shape
interface is declared as sealed, restricting its inheritance to explicitly permitted subclasses, as defined in the permits
clause—namely, Circle
and Rectangle
.
- Circle: Declared as non-sealed, it can be freely extended by other classes.
- Rectangle: Declared as final, it cannot be extended further.
Key Features of Sealed Interfaces:
- Sealed interfaces control inheritance by limiting the set of classes or interfaces that can implement them.
- Permitted subclasses can be:
- Final: Preventing further extension.
- Non-sealed: Allowing unrestricted inheritance.
- Sealed themselves: Continuing inheritance restrictions.
Simplifying Code with Pattern Matching
Pattern matching enhances readability and provides a concise way to deconstruct objects directly in your code. Here’s an example:
public static String handleShape(Shape shape) {
return switch (shape) {
case Circle(double radius) -> "Circle with radius: " + radius;
case Rectangle(double length, double width) ->
"Rectangle with length: " + length + " and width: " + width;
default -> "Unknown Shape!";
};
}
Example Usage
Let’s see this in action:
public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(10.0, 4.0);
System.out.println(handleShape(circle));
System.out.println(handleShape(rectangle));
}
Output:
Circle with radius: 5.0
Rectangle with length: 10.0 and width: 4.0
Conclusion
Sealed interfaces combined with pattern matching enable developers to write structured and expressive code. The ability to match object types and destructure components all in one step allows for cleaner logic and improved readability.
Author: Mohammad J Iqbal