class MyThread extends Thread { MyThread() { System.out.print(" MyThread"); } public void run() { System.out.print(" bar"); } public void run(String s) { System.out.print(" baz"); } } public class TestThreads { public static void main (String [] args) { Thread t = new MyThread() { public void run() { System.out.print(" foo"); } }; t.start(); } } What is the result?

  1. MyThread foo

  2. MyThread bar

  3. foo bar

  4. foo bar baz


Correct Option: A

AI Explanation

To answer this question, let's go through the code step by step:

  1. We have a class MyThread that extends the Thread class.
  2. Inside the MyThread class, there is a constructor that prints "MyThread" when an instance of MyThread is created.
  3. The MyThread class also has two run methods. The first run method does not take any arguments and prints "bar". The second run method takes a string argument and prints "baz".
  4. We have another class called TestThreads with the main method.
  5. In the main method, a new thread t is created as an instance of MyThread with an anonymous inner class.
  6. Inside the anonymous inner class, we override the run method to print "foo".
  7. Finally, the start method is called on the t thread.

Now, let's analyze the options:

Option A) MyThread foo: This option is correct because when we call the start method on the t thread, it executes the overridden run method in the anonymous inner class, which prints "foo". The "MyThread" is printed by the constructor when the MyThread instance is created.

Option B) MyThread bar: This option is incorrect because the overridden run method in the anonymous inner class is executed, which prints "foo" instead of "bar".

Option C) foo bar: This option is incorrect because the "MyThread" is not printed. Only the overridden run method in the anonymous inner class is executed, which prints "foo" and "bar".

Option D) foo bar baz: This option is incorrect because the run method that takes a string argument is not executed. Only the overridden run method in the anonymous inner class is executed, which prints "foo" and "bar".

Therefore, the correct answer is Option A) MyThread foo.

Find more quizzes: