Junior — Middle
What are the advantages and disadvantages of using sealed classes in Java?
sobes.tech AI
Answer from AI
Sealed classes in Java allow restricting the set of classes that can inherit or implement a given class or interface. This provides stricter control over the type hierarchy.
Advantages:
- Increased type safety: the compiler knows all possible subclasses, simplifying verification and processing.
- Improved support for pattern matching and switch, as all options are known in advance.
- Control over extensibility: you can restrict who can inherit, which helps in architecture.
Disadvantages:
- Less flexibility: cannot add new subclasses outside the predefined list.
- May complicate design if the set of inheritors changes frequently.
Example of declaring a sealed class:
public sealed class Shape permits Circle, Rectangle {}
public final class Circle extends Shape {}
public final class Rectangle extends Shape {}
Thus, sealed classes are useful when you need strict control over the inheritance hierarchy.