• Constraints on Permitted Subclasses

    (Carrefour Shops Edition)

    When you define a sealed class in Java, the permitted subclasses must follow specific rules to ensure the system remains consistent and secure. Let’s explore these constraints using our real-world example of Carrefour shops.

    1. Permitted Subclasses Must Be Accessible at Compile Time

    The Java compiler must have access to all permitted subclasses when compiling the sealed class.

    For instance, if you define:

    then at compile time, the compiler must also have access to the full definitions of:

    🟣 CarrefourCity

    🟣 CarrefourMarket

    🟣 CarrefourHyper

    Furthermore, because CarrefourHyper could itself be a sealed class, the compiler would also need access to any of its permitted subclasses, such as CarrefourDrive and CarrefourBio.

    2. Permitted Subclasses Must Directly Extend the Sealed Class

    A permitted class must directly inherit from the sealed class it is listed under.
    You cannot declare a permitted class that is several layers down the inheritance hierarchy.

    Example:

    Here, both CarrefourCity and CarrefourMarket must directly extend CarrefourShop.

    Incorrect example:
    If CarrefourUrbanMarket extends CarrefourMarket, you cannot list CarrefourUrbanMarket in CarrefourShop's permits clause directly.

    3. Permitted Subclasses Must Specify Their Continuation of Sealing

    Each permitted subclass must explicitly state how it continues the sealing behavior using exactly one of the following modifiers:

    🟣 final: No further subclassing allowed.
    Example: CarrefourCity might be final because it has a fixed structure.

    🟣 sealed: Can only be extended by specific permitted subclasses.
    Example: CarrefourHyper could be sealed if it defines specific types like CarrefourDrive and CarrefourBio.

    🟣 non-sealed: Opens the subclass to unrestricted extension.
    Example: CarrefourMarket might be non-sealed to allow new market formats to be added later.

    4. Subclasses Must Be in the Same Module or Same Package

    Depending on the project organization:

    🟣 If you use named modules (like in a modularized Java application), the sealed class and its permitted subclasses must all be part of the same module.

    🟣 If you work with unnamed modules (standard package-based projects), they must be in the same package.

    Example with modules:

    This will compile only if all classes are part of the same module, such as com.carrefour.

    Otherwise, in a simpler project without modules, all classes would need to be placed under the same package (e.g., com.carrefour.shops).

    Quick recap

    broken image