Anonymous Thread subclass overriding run() vs superclass constructor side effects — what prints?\n\nclass MyThread extends Thread \n{\n MyThread() \n {\n System.out.print(" MyThread");\n }\n public void run() \n {\n System.out.print(" bar");\n }\n public void run(String s) \n {\n System.out.println(" baz");\n }\n}\npublic class TestThreads \n{\n public static void main (String [] args) \n {\n Thread t = new MyThread() \n {\n public void run() \n {\n System.out.println(" foo");\n }\n };\n t.start();\n }\n}\n\nChoose the exact output.

Difficulty: Easy

Correct Answer: MyThread foo

Explanation:


Introduction / Context:
This question combines constructor side effects with method overriding. The superclass MyThread prints in its constructor and defines two run methods: run() and an overloaded run(String). The anonymous subclass created in main overrides run().



Given Data / Assumptions:

  • Constructing the anonymous subclass first runs the MyThread() constructor, printing " MyThread".
  • The anonymous subclass overrides run() and prints " foo" using println, which appends a newline.
  • run(String) is just an overload, never called by Thread.start().


Concept / Approach:
Thread.start() always invokes the no-argument run() polymorphically. Overloads such as run(String) are not considered by the thread machinery. Therefore, after construction prints, the overridden run() in the anonymous class runs and prints " foo".



Step-by-Step Solution:

Create new MyThread() { public void run(){ System.out.println(" foo"); } } → constructor prints " MyThread".Call start() → JVM invokes overridden run() → prints " foo".No call to superclass run() or run(String) occurs.


Verification / Alternative check:
Replace println with print and observe spacing differences, but the token order remains MyThread then foo.



Why Other Options Are Wrong:

  • "foo" omits the constructor print.
  • "MyThread bar" would require using the superclass run(), which is overridden.
  • "foo bar" suggests both run methods executed; only one run() is called.


Common Pitfalls:
Confusing overloading with overriding; Thread looks only for run().



Final Answer:
MyThread foo

Discussion & Comments

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