public sealed class Shape
permits Circle, Square, Rectangle {
}
final class Circle extends Shape {
float radius;
}
non-sealed class Square extends Shape {
float side;
}
sealed class Rectangle extends Shape {
float length, width;
}
1. You can see two new keywords: "sealed" and "permits". The second keyword "permits" is optional. If the class extendign a sealed class are in the same file, the permits is default to current package.
2. Subclasses of a seald class can be also sealed, float or none-sealed. One of these modifiers is mandatory but they are exclusive.
Sealed interface similar to classes can be implemented by "permited" list of classes. In next example we implement the interface Expr in dwo record classes we have just learned.
sealed interface Expr
permits ConstantExpr, PlusExpr {
public int eval();
}
record ConstantExpr(int i) implements Expr {
public int eval() { return i(); }
}
record PlusExpr(Expr a, Expr b) implements Expr {
public int eval() { return a.eval() + b.eval(); }
}
Read more: Java Sealed Classes
Read next: Performance Computing