-
Notifications
You must be signed in to change notification settings - Fork 17
Closed
Description
Sealed types was a preview feature in Java 15.
It became part of the language in Java 17.
Sealed types is a feature introduced in Java to enhance the control and security of class access and inheritance.
- Sealed types restrict which other classes or interfaces can extend or implement them.
- When you declare a class as sealed, you specify a limited set of classes or interfaces that can be direct subtypes of the sealed class.
- This ensures that only authorized classes can inherit from the sealed class.
- You define the permitted subtypes using the
permits
keyword in the sealed class declaration.
Example:
public sealed class Shape permits Circle, Triangle {
// ...
}
- In this example, only the
Circle
andTriangle
classes can be direct subtypes of theShape
class. - You can also have a
default
case to allow other classes within the same package to extend the sealed class.
A permitted subclass may be declared non-sealed, then it is open for extension.
public non-sealed class Shape permits Circle, Triangle {
// ...
}
A sealed class imposes three important constraints on its permitted subclasses:
All permitted subclasses must belong to the same module as the sealed class.
Every permitted subclass must explicitly extend the sealed class.
Every permitted subclass must define a modifier: final, sealed, or non-sealed.
Can be used for classes and interfaces. But not for record classes or enums?
To be implemented:
- sealed, non-sealed and permits pseudo-keywords used in the class definition context
- important - these are not reserved keywords, they can be used as identifiers (e.g. variable name)
- use
isKeyword()
token look-ahead instead of string literals in java.g