Java 中的密封类
密封类是限制其他类或接口可以扩展或实现它的类。它允许您定义一组封闭的子类,允许扩展密封类。密封类旨在提供对继承层次结构的更多控制,并确保某些类对子类具有独占访问权限。
要定义密封类,可以在 class 关键字之前使用 seal 修饰符,后跟允许的子类列表:
public sealed class Shape permits Circle, Rectangle, Triangle {
// Common methods and properties for all shapes
}
public final class Circle extends Shape {
// Implementation of Circle class
}
public final class Rectangle extends Shape {
// Implementation of Rectangle class
}
public final class Triangle extends Shape {
// Implementation of Triangle class
}
在上面的示例中,Shape 是一个密封类,它只允许三个子类:Circle、Rectangle 和 Triangle。在此文件之外创建 Shape 的新子类的任何其他尝试都将导致编译错误。
JDK 17 中的接口(如果在 JDK 17 或更高版本中引入):
Java 中的接口是一种定义类必须通过实现接口的方法来遵守的契约的方法。在 JDK 17 中,接口得到了增强,以支持私有方法、私有静态方法和默认方法等新功能。
使用私有方法和私有静态方法,您可以在接口中添加在接口外部无法访问的辅助方法。默认方法提供了一种向现有接口添加新方法而不破坏实现它们的类的方法。
接口中新功能的使用示例(Java 17 或更高版本):
public interface Calculator {
// Regular method
int add(int a, int b);
// Private method
private int validateInput(int number) {
return number >= 0 ? number : 0;
}
// Private static method
private static void log(String message) {
System.out.println("Log: " + message);
}
// Default method
default int subtract(int a, int b) {
return add(a, -b); // Reusing the 'add' method here
}
}
public class BasicCalculator implements Calculator {
@Override
public int add(int a, int b) {
return validateInput(a) + validateInput(b);
}
}
在上面的示例中,Calculator 接口包括常规方法(add)、私有方法(validateInput 和 log)和默认方法(subtract)。BasicCalculator类实现了Calculator接口,提供了add方法的实现,并且可以使用默认方法subtract。