实现Runnable接口的线程的子类 [英] subclass of thread implementing Runnable interface
问题描述
让我困惑的是为什么实现runnable接口的线程的子类不会强制我覆盖run方法。基本上,当我创建实现Runnable的简单类时,它会强制我覆盖run方法。但是当我将普通类作为线程的子类时,它并没有强迫我重写该类。这背后的逻辑是什么?
It confuses me why a subclass of thread that implements a runnable interface doesn't force me to override the run method. Basically, when i create simple class that implements Runnable it forces me to override the run method. But when i made the ordinary class a subclass of thread, it didn't force me to override the class anymore. What's the logic behind this?
推荐答案
当一个非抽象类声明它实现了一个接口时,这意味着class必须具有接口定义的每个方法的具体实现,但这些实现方法不必在类中显式,它们可以从超类继承。在这个具体的例子中, java.lang.Thread
有自己的 public void run()
,哪个子类继承,所以a实现 Runnable
的Thread的子类不需要添加自己的覆盖来满足编译器(虽然它可能确实有用)。
When a non-abstract class declares that it implements an interface, what that means is that the class must have a concrete implementation of every method that the interface defines, but those implementation methods don't have to be explicit in the class, they could be inherited from a superclass. In this specific example java.lang.Thread
has its own public void run()
, which subclasses inherit, so a subclass of Thread that implements Runnable
doesn't need to add its own override to satisfy the compiler (though it probably does to actually be useful).
这篇关于实现Runnable接口的线程的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!