Sage-Code Laboratory
index<--

Sealed Classes

A sealed class is almost like a regular class but there is a restricted list of children classes that can extend it. By sealing a class, you can specify which classes are permitted to extend it and prevent any other arbitrary class from doing so.
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;
}

Notes:

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 Interfaces

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