28.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
28. (Java Question) Threads
What is the output of the following code snippet?
class ThreadDemo implements Runnable {
public void run() {
System.out.println(" running run");
}
public void start() {
System.out.println(" running start");
}
}
class MainClass {
public static void main(String args[]) {
System.out.println("Main Class ");
ThreadDemo thr = new ThreadDemo();
thr.start();
}
}
Pick ONE option
Show answer & explanation
Answer: D. Main Class running start
ThreadDemo overrides the start() method (which is a regular instance method, not the Thread.start() method) to print " running start". Since thr is an instance of ThreadDemo, not a Thread, calling thr.start() invokes the overridden instance method, printing " running start". The run() method is never called. The output is: "Main Class " followed by " running start".
Step-by-step Derivation:
System.out.println("Main Class ")prints "Main Class ".ThreadDemo thr = new ThreadDemo()creates a ThreadDemo object (note: NOT a Thread object).thr.start()calls the overriddenstart()method (an instance method), which prints " running start".- Key insight: Since ThreadDemo is not a subclass of Thread (it only implements Runnable), calling
start()on it calls the overridden instance method, NOT Thread.start(). Therun()method is never invoked. - Final output: "Main Class running start"