问题描述
我具有以下密封接口(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
asfinal
, no other class can extendCat
. - As you've marked
Duck
asnon-sealed
, any class can extendDuck
. -
将扩展
sealed
类的类标记为sealed
,对其施加相同的效果:仅在允许后指定的类
子句可以扩展它. Marking a class that extends a
sealed
class assealed
, applies the same effect on it: Only classes specified after thepermits
clause are allowed to extend it.
将一个类别标记为 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
:
非密封
只是打破密封",因此效果不必在层次结构中继续进行.扩展类是开放的(再次),可以由未知子类本身进行扩展.
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和非密封类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!