Wednesday, August 3, 2022

Quiz yourself: The allowable subtypes in sealed classes

Core Java, Oracle Java Certification, Oracle Java Exam, Oracle Java Preparation, Oracle Java Career, Java Skills, Java Jobs

You should know what the rules say about subclasses being public, protected, and final.

Given the sealed Bird class

public sealed class Bird permits Sparrow {}

Which Sparrow class definitions, when used independently, are valid? Choose two.

A. non-sealed class Sparrow extends Bird { }

B. public class Sparrow extends Bird { }

C. protected class Sparrow extends Bird { }

D. final class Sparrow extends Bird { }

Answer. The normal syntax for a sealed type requires that the type define in the permits section the list of allowed direct subtypes. In this question, the Bird class enumerates only one allowed direct subclass, which is Sparrow.

The direct subtypes of a sealed type are subject to some constraints; they must carry one of the following three listed modifiers, which cause the effects noted:

◉ non-sealed, in which case the non-sealed type can itself have arbitrary subtypes

◉ sealed, in which case this subtype must also declare a nonempty permits clause enumerating at least one existent subtype

◉ final, in which case the type must be a concrete class and no further subclasses are allowed

In the code of the question, only options A and D fulfill these requirements; thus, those options are correct.

Option B would be valid as a regular subclass of a Bird if the Bird class were not sealed. Since Bird is sealed, however, Sparrow is unacceptable because it fails to satisfy the constraints listed above. From this, you know that option B is incorrect.

Option C is also incorrect because the constraints listed are not met: The protected modifier does not satisfy the constraints. In addition, in the question it appears that the classes listed are all top-level classes, and the protected modifier may be applied only to fields, methods, constructors, or nested types, not to top-level types.

Conclusion. The correct answers are options A and D.

Source: oracle.com

Related Posts

0 comments:

Post a Comment