Difficulty: Easy
Correct Answer: Pine
Explanation:
Introduction / Context:
This code tests runtime type checks using instanceof and the impact of ordering in an if/else-if chain. The declared type is Tree, but the actual (runtime) type is Pine, a subclass of Tree.
Given Data / Assumptions:
Concept / Approach:
instanceof tests the runtime type. A Pine object is also a Tree due to inheritance, but the first condition explicitly checks Pine and therefore succeeds before reaching the broader Tree check.
Step-by-Step Solution:
Evaluate tree instanceof Pine → true. Print "Pine". Remaining else-if blocks are skipped.
Verification / Alternative check:
If the order were reversed (Tree first), it would print "Tree" because that condition would capture all subclasses too. Ordering matters.
Why Other Options Are Wrong:
"Tree" would be printed only if the first condition did not match or if it appeared first. "Oak"/"Forest"/"Oops" do not apply to a Pine instance.
Common Pitfalls:
Thinking declared type governs instanceof; forgetting that only the first true condition in an if/else-if chain executes.
Final Answer:
Pine
Discussion & Comments