Anonymous Thread subclass overriding run() vs superclass constructor side effects — what prints? class MyThread extends Thread { MyThread() { System.out.print(" MyThread"); } public void run() { System.out.print(" bar"); } public void run(String s) { System.out.println(" baz"); } } public class TestThreads { public static void main (String [] args) { Thread t = new MyThread() { public void run() { System.out.println(" foo"); } }; t.start(); } } Choose 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