subclass of thread implementing Runnable interface

▼魔方 西西 提交于 2019-12-14 03:53:30

问题


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?


回答1:


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).




回答2:


This is because Thread itself implements run().

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

By default it does nothing. If we extend a Thread we implement this method so that it does something useful



来源:https://stackoverflow.com/questions/30543929/subclass-of-thread-implementing-runnable-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!