Difficulty: Easy
Correct Answer: i = 3
Explanation:
Introduction / Context:
The snippet demonstrates use of a local class inside main, upcasting an instance to Object, then downcasting back to the local class type. It checks understanding of how Java retains runtime type information and whether such casts are valid.
Given Data / Assumptions:
Concept / Approach:
Java preserves the actual runtime class (Foo) for objects even when stored in a supertype reference (Object). Downcasting succeeds when the runtime type is compatible with the target type. Accessing foo.i then prints 3.
Step-by-Step Solution:
Verification / Alternative check:
If o referenced a different type, downcasting would throw ClassCastException. Here the types match exactly.
Why Other Options Are Wrong:
Common Pitfalls:
Assuming local classes cannot be referenced or cast; confusing compile-time and runtime typing.
Final Answer:
i = 3
Discussion & Comments