In Java, what does this code print when an anonymous class overrides hashCode()?\n\npublic static void main(String[] args) \n{\n Object obj = new Object() \n {\n public int hashCode() \n {\n return 42;\n }\n }; \n System.out.println(obj.hashCode()); \n}

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:

  • An anonymous subclass of Object is created.
  • It overrides 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:

Create an anonymous subclass of Object.Override 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:

  • Compile errors: none occur in this valid snippet.
  • Runtime exception: nothing throws here.
  • 0: that would require the inherited implementation to coincidentally return 0, which it does not guarantee, and anyway we override to 42.


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

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