document Particular person(String identify, int age) {}
if (obj instanceof Particular person particular person) {
System.out.println("Title: " + particular person.identify());
}
Now let’s think about a extra conventional instance. Geometric shapes are a basic solution to reveal how sealed interfaces work with data, they usually make sample matching particularly clear. The class of this mixture is obvious in change expressions (launched in Java 17), which allow you to write concise, kind‑secure code that resembles algebraic knowledge sorts in purposeful languages:
sealed interface Form permits Rectangle, Circle, Triangle {}
document Rectangle(double width, double top) implements Form {}
document Circle(double radius) implements Form {}
document Triangle(double base, double top) implements Form {}
public class RecordPatternMatchingExample {
public static void most important(String[] args) {
Form form = new Circle(5);
// Expressive, type-safe sample matching
double space = change (form) {
case Rectangle r -> r.width() * r.top();
case Circle c -> Math.PI * c.radius() * c.radius();
case Triangle t -> t.base() * t.top() / 2;
};
System.out.println("Space = " + space);
}
}
Right here, the Form
kind is a sealed interface, allowing solely Rectangle
, Circle
, and Triangle
. As a result of this set is closed, the change is exhaustive and requires no default department.
Utilizing data as knowledge switch objects
Data excel as knowledge switch objects (DTOs) in trendy API designs comparable to REST, GraphQL, gRPC, or inter‑service communication. Their concise syntax and constructed‑in equality make data splendid for mapping between service layers. Right here’s an instance: