Junior — Middle
How does using Sealed Interface differ from Enum in Java?
sobes.tech AI
Answer from AI
Sealed Interface and Enum in Java serve different purposes, although both restrict the set of permissible implementations.
-
Enum is a special type that represents a fixed set of constants. It is ideal when you need to define a limited list of values, such as days of the week or states.
- All values are listed in one place.
- Enum automatically supports methods like
values(),valueOf(). - Does not support inheritance (cannot extend an enum).
-
Sealed Interface (or Sealed Class) is a mechanism to restrict inheritance hierarchy. It explicitly specifies which classes can implement the interface or extend the class.
- Allows creating more flexible and extendable hierarchies.
- Can have different implementations with different logic.
- Used to control extensibility, for example, in design patterns.
Example:
sealed interface Shape permits Circle, Rectangle {}
final class Circle implements Shape {
double radius;
}
final class Rectangle implements Shape {
double width, height;
}
Thus, Enum is a fixed set of values, while Sealed Interface is a way to control who can implement the interface, maintaining implementation flexibility.