Java MCQ: Which method must be overridden when implementing the Runnable interface?
Answer:
Explanation:
When implementing the Runnable
interface in Java, you must override the run()
method. The run()
method contains the code that defines the task to be executed by the thread. The Runnable
interface is part of the java.lang
package and is a functional interface with a single abstract method: run()
.
Here’s an example of implementing the Runnable
interface:
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
In this example, the MyRunnable
class implements the Runnable
interface and overrides the run()
method to print a message. A new Thread
object is created with myRunnable
as its target, and the thread is started using the start()
method, which in turn invokes the run()
method.
Using the Runnable
interface is a common approach in Java for defining tasks that can be executed by threads. It provides flexibility by allowing the task to be separated from the thread itself, enabling the same task to be executed by different threads.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html