Friday, February 12, 2021

Module and package constraint for permitted sub types

In sealed classes, this constraint apply.

That when you are using modules, the sealed class and its permitted sub types must be defined within the same module. 

If you are not using modules, the sealed class and its permitted sub types must be defined within the same package. 

The below code will not compile unless they are included as part of the same module

package samples.j15.sealed;

import samples.j15.sealed.impl.*;

public sealed interface Pet permits Cat {

}
package samples.j15.sealed.impl;

import samples.j15.sealed.Pet; 

public non-sealed class Cat implements Pet {

}

This is not allowed because the sealed class Pet and its permitted sub type Cat are in different packages - samples.j15.sealed and samples.j15.sealed.impl respectively. 

This code will compile only if these 2 packages are part of the same module. 

To include the above to packages, just create a module-info.java file at the root folder, with only the module name as in the following declaration 

module sealed.samples {
    
}

This will make the two packages part of the sealed.samples module. Now this code will compile because they are now part of the same module.

Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Sealed-classes/Module-and-package-constraint

No comments:

Post a Comment