Java local classes, casting through Object, and type safety at runtime: what is printed?\n\npublic class Test {\n public static void main(String[] args) {\n class Foo { public int i = 3; }\n Object o = (Object) new Foo();\n Foo foo = (Foo) o;\n System.out.println("i = " + foo.i);\n }\n}

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:

  • Local class Foo is defined inside main with a public field i initialized to 3.
  • Object o references a Foo instance after upcast.
  • Downcast Foo foo = (Foo) o is type-correct at runtime.


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:

Create Foo with i = 3.Upcast to Object: no loss of runtime type.Downcast back to Foo: succeeds (o is a Foo).Access field i and print → "i = 3".


Verification / Alternative check:
If o referenced a different type, downcasting would throw ClassCastException. Here the types match exactly.



Why Other Options Are Wrong:

  • Compilation fails: Local classes are allowed; the code is valid.
  • ClassCastException: Would occur only if the runtime type were incompatible.
  • i = 5 / Empty output: No such assignment or suppression occurs.


Common Pitfalls:
Assuming local classes cannot be referenced or cast; confusing compile-time and runtime typing.



Final Answer:
i = 3

More Questions from Declarations and Access Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion