什么是 Java 中的密封类和 JDK 17 中的接口,以及如何使用它们?

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Q shen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值