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();
    }
}
foo
MyThread foo
MyThread bar
foo bar
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.

Golda said:   5 years ago
I got an output as MyThread foo. I agree with the given answer.

Chandhu said:   6 years ago
I executed the code and I got the Output:: foo.

Is it right? If not, please explain.

Erik said:   9 years ago
Would like to see the @Override like this: (isn't that mandatory).

@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();

Kannan said:   1 decade ago
My system output is :foo.

Please explain.

Post your comments here:

Your comments will be displayed after verification.