简体   繁体   中英

class is implementing runnable interface but not defining the run method

class Qus3 extends Thread implements Runnable {

    public static void main(String args[]) {
        Qus3 q3 = new Qus3();
        q3.start();
    }
}

This code compiles without any error but isn't it necessary to define all the methods of an interface otherwise declare the class abstract.In the above code Class hasn't been declared abstract and run() is also not defined by the class although it has implemented Runnable interface, why the code is still correct?

Thread implements Runnable. from the API :

public void run()

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

Subclasses of Thread should override this method.

So you won't get a compile error, but run won't do anything. The newly-started thread will execute the empty run method and terminate.

Your code is correct, but it's a better idea to avoid extending Thread, create a separate Runnable and pass that in to the new thread. That way not only can you extend something other than Thread, but you won't risk accidentally overriding thread methods.

线程覆盖运行,因为您扩展了Thread,所以实现了run方法。

Class implements Runnable but also extends Thread. Internally Thread also implements Runnable and provides implementation for it. That is the reason it compiles successfully.

If you remove extends Thread , you will see it will give compilation error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM