Java sealed classes:修订间差异

来自WHY42
 
第35行: 第35行:
* if you want a sub class to be extended by the user, make it `non-sealed`
* if you want a sub class to be extended by the user, make it `non-sealed`


(The final modifier can be considered a special case of sealing, where extension/implementation is prohibited completely. That is, final is conceptually equivalent to sealed plus a permits clause which specifies nothing, though such a permits clause cannot be written.)




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

2024年9月19日 (四) 01:53的最新版本

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`

(The final modifier can be considered a special case of sealing, where extension/implementation is prohibited completely. That is, final is conceptually equivalent to sealed plus a permits clause which specifies nothing, though such a permits clause cannot be written.)