跳到主要内容

1 篇博文 含有标签「JDK17」

查看所有标签

JDK 17 LTS 版本重大特性详解

· 阅读需 8 分钟

Java 17 是继 JDK 11 之后的又一个长期支持版本(LTS),于2021年9月14日正式发布。作为一个 LTS 版本,它带来了许多重要的新特性和改进,这些特性将在未来很长一段时间内得到支持。本文将详细介绍 JDK 17 中的主要变更和新特性。

1. 密封类(正式发布)

密封类在 JDK 17 中正式成为标准特性:

public sealed interface Shape 
permits Circle, Rectangle, Triangle {
double area();
}

public final class Circle implements Shape {
private final double radius;

public Circle(double radius) {
this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

// sealed 实现类
public sealed class Rectangle implements Shape
permits Square {
private final double width;
private final double height;

public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

@Override
public double area() {
return width * height;
}
}

// non-sealed 实现类
public non-sealed class Triangle implements Shape {
private final double base;
private final double height;

public Triangle(double base, double height) {
this.base = base;
this.height = height;
}

@Override
public double area() {
return 0.5 * base * height;
}
}
java

主要优点:

  • 精确控制类型层次结构
  • 增强代码安全性和可维护性
  • 与模式匹配完美配合
  • 支持接口和类的密封