Sail E0 Webinar
Question


What will be the output of the program?


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();
}
}
Options:
A .  foo
B .  MyThread foo
C .  MyThread bar
D .  foo bar
Answer: Option B

Option B is correct because in the first line of main we're constructing an instance of an 

anonymous inner class extending from MyThread. So the MyThread constructor runs 

and prints "MyThread". The next statement in main invokes start() on the new thread 

instance, which causes the overridden run() method (the run() method defined in the 

anonymous inner class) to be invoked, which prints "foo"



Was this answer helpful ?
Next Question

Submit Solution

Your email address will not be published. Required fields are marked *

Latest Videos

Latest Test Papers