Language Upgrades · interview question
Given the following code, what would be the correct way to allow 'GiftCard' to extend 'Payment'? sealed class Payment permits CreditCard, PayPal {} final class CreditCard extends Payment {} non-sealed class PayPal extends Payment {}?
Multiple choiceMediumchapter-12-curatedpremiumlanguage-upgradessealed-classes
sealed class Payment permits CreditCard, PayPal, GiftCard {}Answer and explanation
Correct answer
A. Add 'GiftCard' to the permits clause of 'Payment'.
Why
To allow 'GiftCard' to extend 'Payment', you must add 'GiftCard' to the 'permits' clause of the 'Payment' class. This explicitly allows 'GiftCard' to be part of the sealed class hierarchy, maintaining control over subclassing.
Test yourself on Language Upgrades
A free test with instant, explained results. No account needed.
More Language Upgrades questions
- Which of the following is NOT a valid modifier for a class extending a sealed class?
- How does pattern matching for 'instanceof' improve maintainability in Java?
- What must be true for a class to extend a sealed class and be marked as 'non-sealed'?
- Which Java keyword would you use to specify the classes that can extend a sealed class?
- Given a sealed interface, which of the following is NOT a correct way to implement it?
- Why might an architect choose sealed classes for an e-commerce domain model?