[英]What is the difference between a final and a non-sealed class in Java 15's sealed-classes feature?
我有以下密封接口(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
和non-sealed
的區別? final
阻止我創建其他子類,但non-sealed
適用於Duck
的行為是什么?
Cat
標記為final
,因此沒有其他類可以擴展Cat
。Duck
標記為non-sealed
,因此任何類都可以擴展Duck
。 將類標記為sealed
,所有直接擴展的類(在permits
子句之后的類)都必須標記為final
、 sealed
或non-sealed
:
將擴展sealed
類的類標記為sealed
,對其應用相同的效果:只有在permits
子句之后指定的類才允許擴展它。
non-sealed
只是“破壞密封”,因此效果不必沿層次結構向下傳遞。 擴展類是開放的(再次)被未知子類本身擴展。
final
是有效一樣sealed
而不之后指定任何類permits
條款。 請注意,在permits
后不指定任何內容是不可能的,因此sealed
不能替換final
。
final 類有零個子類,這意味着沒有其他類可以擴展它。 任何類都可以擴展非密封類。
當您將類標記為密封時,只有允許的子類可以擴展它,並且只能將這些修飾符設為 final、sealed 或 non-sealed:
public sealed class NumberSystem
// The permits clause has been omitted
// as all the subclasses exists in the same file.
{ }
non-sealed class Decimal extends NumberSystem { .. }
final class NonRecurringDecimal extends Decimal {..}
final class RecurringDecimal extends Decimal {..}
盡管 NumberSystem 根級別層次結構對一組已知類是封閉的,但您可以使用非密封關鍵字允許打開子層次結構。
密封和非密封組合允許您限制層次結構的部分而非全部。
在下圖中,我們將密封類 NumberSystem 的根層次結構限制為一組已知的子類。 但是,非密封的Decimal 類允許任何未知的子類(例如 RecurringDecimal)擴展它。
final 和 non-sealed class 有一些區別。
final class:你不能繼承這個class。我的意思是你不能將這個class擴展到其他class。
非密封class:你可以從別人那里繼承這個class。
例如:
此密封接口只允許Cat&Duck class接口。注意Cat&Duck必須是final,非密封或密封class
public sealed interface Animal permits Cat, Duck {
String makeSound();
}
現在,我正在創建 Cat & Duck class。這里的 Cat 是最終的 class,另一個是未密封的 class。
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";
}
}
因此,如果您可以嘗試繼承 Cat class,則不能,因為 Cat class 是最終的,所以會出現編譯錯誤。另一方面,Duck class 是可擴展的,因為它是非密封的 class就像,
//Got Error
public class MyCat extands Cat {
.......
}
//Error not show.Duck class is extendable
public class MyDuck extands Duck {
.....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.