java – 为什么没有调用实现Runnable接口的类的构造函数?
发布时间:2020-12-15 05:11:28 所属栏目:Java 来源:网络整理
导读:我尝试使用实现Runnable Interface的类的构造函数.但我很惊讶地发现它从未被调用过.调用了run()方法,但是从未调用过构造函数.我写了一个简单的示例代码来显示这种现象.任何人都可以解释为什么会这样吗? public class MyRunner implements Runnable { public
我尝试使用实现Runnable Interface的类的构造函数.但我很惊讶地发现它从未被调用过.调用了run()方法,但是从未调用过构造函数.我写了一个简单的示例代码来显示这种现象.任何人都可以解释为什么会这样吗?
public class MyRunner implements Runnable { public void MyRunner() { System.out.print("Hi I am in the constructor of MyRunner"); } @Override public void run() { System.out.println("I am in the Run method of MyRunner"); } public static void main(String[] args){ System.out.println("The main thread has started"); Thread t = new Thread(new MyRunner()); t.start(); } } 解决方法
将public void MyRunner()更改为public MyRunner()(无返回类型). public void MyRunner()不是构造函数,它是一个方法.构造函数声明没有返回类型.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |