Language Upgrades · interview question
Consider a sealed class hierarchy where you have a base class Order and two subclasses, OnlineOrder and InStoreOrder. If you add a new subclass, PhoneOrder, what change is necessary in a switch expression handling Order?
Multiple choiceHardchapter-12-curatedpremiumlanguage-upgradespattern-matching
Answer and explanation
Correct answer
D. Update the switch expression to handle PhoneOrder to ensure exhaustiveness.
Why
In a sealed class hierarchy, adding a new subclass requires updating the switch expression to explicitly handle the new subclass, ensuring that the code remains exhaustive and no cases are overlooked.
Test yourself on Language Upgrades
A free test with instant, explained results. No account needed.
More Language Upgrades questions
- Which of the following is a correct use of a switch expression in Java?
- How can sealed classes help in managing a complex class hierarchy in an e-commerce application?
- When using a switch expression with pattern matching, what is a potential benefit compared to using multiple if-else…
- How does pattern matching for instanceof improve code readability and maintainability?
- How does pattern matching in switch expressions enhance type safety?
- In Java, how does pattern matching for 'instanceof' improve code readability?