document Particular person(String identify, int age) {}
if (obj instanceof Particular person particular person) {
System.out.println("Identify: " + particular person.identify());
}
Now let’s take into account a extra conventional instance. Geometric shapes are a basic option to exhibit how sealed interfaces work with data, they usually make sample matching particularly clear. The class of this mix is clear in change expressions (launched in Java 17), which allow you to write concise, kind‑secure code that resembles algebraic information varieties in practical 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 foremost(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 information switch objects
Information excel as information switch objects (DTOs) in trendy API designs similar to REST, GraphQL, gRPC, or inter‑service communication. Their concise syntax and constructed‑in equality make data preferrred for mapping between service layers. Right here’s an instance: