Difficulty: Easy
Correct Answer: 42
Explanation:
Introduction / Context:
This checks your understanding of anonymous inner classes and method overriding in Java. The Object class defines hashCode(), and an anonymous subclass can override it. Calls dispatch dynamically to the most specific override at runtime.
Given Data / Assumptions:
Object is created.hashCode() to return the constant 42.System.out.println(obj.hashCode()) is invoked.
Concept / Approach:
Method dispatch for instance methods is virtual by default in Java. Even if the reference type is Object, the actual method executed is the override in the anonymous subclass. Therefore, the printed value is whatever the override returns.
Step-by-Step Solution:
hashCode() to return 42.Call obj.hashCode() → dynamic dispatch to the override → 42.
Verification / Alternative check:
If the override were misspelled (e.g., hashcode()), no override would occur and the inherited implementation would run, typically returning a JVM-specific value. Here the method name and signature match exactly, so the override is valid.
Why Other Options Are Wrong:
Common Pitfalls:
Misspelling method names (case matters) or misusing annotations. You can add @Override to catch signature mistakes at compile time.
Final Answer:
42
Discussion & Comments