关于java密封类限制父类和子类只能在一个包下

比如:
原本子类在service/impl包下
父类在service包下。
而密封类限制父类和子类只能在一个包下,
那么密封类不能用于这样的模式了?


回答:

并不一定非得在同一个包下。

Java 规范原文:

REF: JEP-360 Sealed Classes:

A sealed class imposes three constraints on its permitted subclasses (the classes specified by its permits clause):

  1. The sealed class and its permitted subclasses must belong to the same module, and, if declared in an unnamed module, the same package.
  2. Every permitted subclass must directly extend the sealed class.
  3. Every permitted subclass must choose a modifier to describe how it continues the sealing initiated by its superclass:

    • A permitted subclass may be declared final to prevent its part of the class hierarchy from being extended further.
    • A permitted subclass may be declared sealed to allow its part of the hierarchy to be extended further than envisaged by its sealed superclass, but in a restricted fashion.
    • A permitted subclass may be declared non-sealed so that its part of the hierarchy reverts to being open for extension by unknown subclasses. (A sealed class cannot prevent its permitted subclasses from doing this.)

注意加粗部分。


回答:

看了一下楼上的,试了一下,创建一个module-info.java,就可以跨包


service 和 impl 这种包很有可能会暴露出去给人实现, 就比如dubbo这种框架,service 和 impl 在不同的地方,就更不推荐你用sealed这种关键字去搞限制


个人理解, 欢迎大佬纠正: sealed 这种更像是枚举的扩展玩法, 因为他锁定了一个接口或者抽象类 or 类只有 有限的 final 子类, 子类可以提供不同的构造器或者方法去实现自己

以上是 关于java密封类限制父类和子类只能在一个包下 的全部内容, 来源链接: utcz.com/p/944411.html

回到顶部