When a sealed class and its permitted subclasses are spread across different packages within the same module in Java, the following implications and behaviors apply:
Key Points:
-
- Sealed classes and their permitted subclasses must be declared in the same module. This ensures that the class hierarchy is well-defined and controlled within the module.
- The
permits
clause in the sealed class declaration specifies which classes are allowed to extend or implement it. These permitted subclasses must be declared in the same module as the sealed class.
-
- While sealed classes and their permitted subclasses can be spread across different packages within the same module, they must still adhere to the visibility rules of Java. This means that the subclasses must have appropriate access modifiers to be visible and usable within the module.
- The subclasses can be declared as
public
, protected
, or package-private (default access), but they must be accessible within the module where the sealed class is defined.
-
- During compilation, the Java compiler ensures that all permitted subclasses are known and declared within the same module. This allows for compile-time checking of the class hierarchy, ensuring that no unauthorized subclasses can extend the sealed class.
- At runtime, the classloader mechanism ensures that the sealed class and its permitted subclasses are loaded from the same module. The classloader follows the delegation model, where classes are loaded from parent to child classloaders, ensuring that classes are loaded only once and maintaining their uniqueness.
-
-
Benefits of Sealed Classes:
Example Scenario:
Consider a module com.example
with two packages com.example.shapes
and com.example.errors
. The sealed class Shape
is defined in com.example.shapes
, and its permitted subclasses Circle
and Rectangle
are defined in com.example.shapes
and com.example.errors
, respectively.
public sealed class Shape permits Circle, Rectangle {
}
public final class Circle extends Shape {
}
public final class Rectangle extends Shape {
}
- The sealed class
Shape
is declared in com.example.shapes
.
- The permitted subclasses
Circle
and Rectangle
are declared in com.example.shapes
and com.example.errors
, respectively.
- The classloader ensures that all these classes are loaded from the same module
com.example
, maintaining the integrity of the sealed class hierarchy.