Sealed Classes Flashcards
How do we define sealed classes?
public sealed class Name permits SomeClass {}
Each class that is permitted must extend class that permits it:
public final class SomeClass extends Name {}
Instead of “final”, there can be “sealed” and “non-sealed”
Both classes need to be in the same package.
What is the purpose of “final” in classes that extend some sealed class?
It is there to block that class of being extended.
What is the purpose of “non-sealed” in classes that extend some sealed class?
It opens sealed classes to other classes.
When can “permits” be omitted?
When class that would be permitted is in the same java file, nested class or in same named module.
How do we define sealed interfaces?
All rules apply as to sealed classes, but difference is that interfaces can permit other interfaces and classes
Can sealed classes permit interfaces?
No, because interfaces don’t implement classes.