简体   繁体   English

class正在实现runnable接口,但没有定义run方法

[英]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? 这段代码编译没有任何错误,但是没有必要定义接口的所有方法,否则声明类抽象。在上面的代码中,Class没有被声明为abstract而run()也没有被类定义,尽管它已经实现了Runnable接口,为什么代码仍然正确?

Thread implements Runnable. 线程实现了Runnable。 from the API : 来自API

public void run() public void run()

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; 如果使用单独的Runnable运行对象构造此线程,则调用该Runnable对象的run方法; otherwise, this method does nothing and returns. 否则,此方法不执行任何操作并返回。

Subclasses of Thread should override this method. Thread的子类应该重写此方法。

So you won't get a compile error, but run won't do anything. 所以你不会得到编译错误,但run不会做任何事情。 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. 您的代码是正确的,但最好避免扩展Thread,创建一个单独的Runnable并将其传递给新线程。 That way not only can you extend something other than Thread, but you won't risk accidentally overriding thread methods. 这样,你不仅可以扩展Thread之外的其他东西,而且不会有意外覆盖线程方法的风险。

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

Class implements Runnable but also extends Thread. 类实现了Runnable,但也扩展了Thread。 Internally Thread also implements Runnable and provides implementation for it. 内部线程还实现了Runnable并为其提供了实现。 That is the reason it compiles successfully. 这就是它成功编译的原因。

If you remove extends Thread , you will see it will give compilation error. 如果删除extends Thread ,您将看到它将给出编译错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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