Java 15的密封类功能中的final和非密封类有什么区别? [英] What is the difference between a final and a non-sealed class in Java 15's sealed-classes feature?

查看:51
本文介绍了Java 15的密封类功能中的final和非密封类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下密封接口(Java 15):

I have the following sealed interface (Java 15):

public sealed interface Animal permits Cat, Duck {

    String makeSound();
}

此接口由2个类实现:

public final class Cat implements Animal {

    @Override
    public String makeSound() {
        return "miau";
    }
}

public non-sealed class Duck implements Animal {

    @Override
    public String makeSound() {
        return "quack";
    }
}

有人可以告诉我最终非密封之间的区别吗? final 使我无法创建其他子类,但是未密封 Duck 的行为是什么?

Can someone tell me the difference between final and non-sealed? final stops me from creating other sub-classes but what behavior does non-sealed apply to Duck?

推荐答案

  • 您已经将 Cat 标记为 final ,其他任何类别都不能扩展 Cat .
  • 当您将 Duck 标记为未密封时,任何类都可以扩展 Duck .
    • As you've marked Cat as final, no other class can extend Cat.
    • As you've marked Duck as non-sealed, any class can extend Duck.
    • 将一个类别标记为 sealed 时,所有直接扩展的类别( permits 子句之后的类别)都必须标记为 final 密封非密封:

      When marking a class as sealed, all directly extending classes (the ones after the permits clause) have to be marked either as final, sealed or non-sealed:

      • 将扩展 sealed 类的类标记为 sealed ,对其施加相同的效果:仅在允许后指定的类子句可以扩展它.

      • Marking a class that extends a sealed class as sealed, applies the same effect on it: Only classes specified after the permits clause are allowed to extend it.

      非密封只是打破密封",因此效果不必在层次结构中继续进行.扩展类是开放的(再次),可以由未知子类本身进行扩展.

      non-sealed just "breaks the seal", so the effect doesn't have to be carried on down the hierarchy. The extending class is open (again) for being extended by unknown subclasses itself.

      最终 sealed 有效地相同,在 permits 子句之后没有指定任何类的情况下.请注意,在许可之后不能指定任何内容,因此 sealed 不能替换 final .

      final is effectively the same as sealed without any class specified after the permits clause. Notice that specifying nothing after permits is not possible, so sealed cannot replace final.

      这篇关于Java 15的密封类功能中的final和非密封类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆