Java 15引入了密封类(Sealed Classes),这是一个新的特性,旨在增强代码的安全性和可维护性。通过限制某个类或接口的子类型数量,开发者可以更好地控制继承结构,从而减少潜在的错误和不必要的复杂性。
密封类允许一个类或接口声明其仅能被特定的其他类或接口所扩展或实现。这意味着,只有那些明确被允许的类可以继承或实现密封类,其他任何类都不能这样做。这有助于构建更安全、更易于理解的继承层次结构。
sealed
:用于标记一个类或接口为密封。permits
:指定哪些类可以扩展或实现该密封类。non-sealed
:用于在密封类中嵌套定义非密封类。密封类特别适用于需要对类的继承进行严格控制的场景,例如:
以下是一个简单的例子,展示如何使用密封类来定义一个有限的继承结构。
public sealed class Shape permits Circle, Rectangle, Triangle {
// 这个类只能被Circle、Rectangle和Triangle继承
}
public final class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
}
public final class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
}
public final class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getBase() {
return base;
}
public double getHeight() {
return height;
}
}
如果尝试创建一个不在permits
列表中的子类,编译器会报错。例如:
// 编译错误:The type Square is not allowed to extend or implement the sealed type Shape
public class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
public double getSide() {
return side;
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);
Shape triangle = new Triangle(3.0, 7.0);
System.out.println("Circle radius: " + ((Circle)circle).getRadius());
System.out.println("Rectangle dimensions: " + ((Rectangle)rectangle).getWidth() + "x" + ((Rectangle)rectangle).getHeight());
System.out.println("Triangle base and height: " + ((Triangle)triangle).getBase() + ", " + ((Triangle)triangle).getHeight());
}
}
non-sealed
关键字定义一个非密封的子类,允许其继续被扩展。