Java Programming - Threads - Discussion
Discussion Forum : Threads - Finding the output (Q.No. 1)
1.
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();
}
}
Answer: Option
Explanation:
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"
Discussion:
5 comments Page 1 of 1.
Erik said:
1 decade ago
Would like to see the @Override like this: (isn't that mandatory).
@Override
public void run()
{
System.out.println(" foo");
}
@Override
public void run()
{
System.out.println(" foo");
}
Siva said:
1 decade ago
Here TestThreads class cannot extending the Thread or MyThread class then how it is possible to override run();
Chandhu said:
7 years ago
I executed the code and I got the Output:: foo.
Is it right? If not, please explain.
Is it right? If not, please explain.
Golda said:
6 years ago
I got an output as MyThread foo. I agree with the given answer.
Kannan said:
1 decade ago
My system output is :foo.
Please explain.
Please explain.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers