Five statements about sealed classes, but not all of them are true
Which statement is true about a sealed class? Choose one.
A. All its subtypes must be in the same package.
B. Under some conditions, it can have direct subclasses that are not listed in a permits clause.
C. The sealed class is implicitly final.
D. The sealed class is implicitly immutable.
E. The sealed class may not be instantiated directly.
Answer. Option A is incorrect because a sealed class can be extended by a class in a different package. However, there are two limitations.
◉ The subclass must be listed in the permits section of the sealed class.
◉ The subclass must be in the same named module as the sealed class.
Option B is correct. If the entirety of a sealed-type hierarchy is coded in a single compilation unit (source file) and the base sealed type does not have a permits clause, some of the types in the source file can declare that they are subtypes of the base sealed type. Such types must conform to the other rules for members of a sealed-type hierarchy, notably that they must themselves be sealed, non-sealed, or final.
Two points are worth making here.
First, if a permits clause exists on a sealed type, the only permitted direct subtypes will be those listed in that clause. The ability to have direct subtypes that are not listed in a permits clause is specifically allowed when no permits clause exists and all children are in the same source file as the parent.
Second, if a sealed type has a direct subtype that is declared sealed, the children of that subtype are not listed in the parent sealed type’s permits clause; instead they’re listed in any such clause on the subtype. Similarly, if the child type is non-sealed, it can have any number of children not listed in any permits clause.
Option C is incorrect because a sealed class can be extended, as mentioned above.
Option D is also incorrect because the “sealedness” of a class does not impact its immutability. Immutability or lack of immutability is a consequence of the logic defined in the implementation.
In addition, option E is incorrect. A sealed class can be directly instantiated (unless some other feature prevents this, for example, if the class is also abstract).
Conclusion. The correct answer is option B.
Source: oracle.com
0 comments:
Post a Comment