Java sealed classes:修订间差异

来自WHY42
(创建页面,内容为“Goals of sealed classes: * Allow the author of a class or interface to control which code is responsible for implementing it. * Provide a more declarative way than access modifiers to restrict the use of a superclass. * Support future directions in pattern matching by providing a foundation for the exhaustive analysis of patterns. = Syntax = Option1: define inner classes: <syntaxhighlight lang="java"> public abstract sealed class Chinese { final class Sim…”)
 
第19行: 第19行:


Option2:
Option2:
<syntaxhighlight lang="java">
public abstract sealed class Language permits English, Chinese{
}
// the permitted class is either final, sealed or non-sealed
public final class English extends Language{
}
</syntaxhighlight>
= Difference between sealed/final =
* both sealed/final class could not be extended again
* final class does not have sub classes
* sealed class contains sub classes
* if you want a sub class to be extended by the user, make it `non-sealed`




[[Category:Java]]
[[Category:Java]]

2024年9月19日 (四) 01:51的版本

Goals of sealed classes:

  • Allow the author of a class or interface to control which code is responsible for implementing it.
  • Provide a more declarative way than access modifiers to restrict the use of a superclass.
  • Support future directions in pattern matching by providing a foundation for the exhaustive analysis of patterns.

Syntax

Option1: define inner classes:

public abstract sealed class Chinese {
    final class SimplifiedChinese extends Chinese{}
    final class TradictionalChinese extends Chinese{}
}

// a sealed class could not be extended, otherwise you get an compiler error:
// public class Other extends Chinese {}
// 'Other' is not allowed in the sealed hierarchy

Option2:

public abstract sealed class Language permits English, Chinese{
}
// the permitted class is either final, sealed or non-sealed
public final class English extends Language{
}

Difference between sealed/final

  • both sealed/final class could not be extended again
  • final class does not have sub classes
  • sealed class contains sub classes
  • if you want a sub class to be extended by the user, make it `non-sealed`