猿问

Java中用循环来这样创建对象,不是应该引用重名报错吗?为什么不报?

循环第二次的时候,就有一个重名的my了呀?为什么还是能正常运行,不报错?

慕神8447489
浏览 945回答 5
5回答

呼唤远方

你的my定义的是局部变量,每执行一次for循环都重新定义了变量。即使你把变量放在循环外面定义,java中不会报错,只是变量存的地址会覆盖掉之前的变量。

慕田峪4524236

直接上代码:public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 3; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread thread = new Thread();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; thread.start();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(thread.getName());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}// 运行结果:// Thread-0// Thread-1// Thread-2如果你要指定名字,你应该这样来做:public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Thread thread = new Thread("我的线程");&nbsp; &nbsp; &nbsp; &nbsp; thread.start();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(thread.getName());&nbsp; &nbsp; }}//运行结果://我的线程

慕勒3428872

my指向不同的MyThread实例对象罢了my ⇢ new MyThread() //老的↘ new Mythread() //新的
随时随地看视频慕课网APP

相关分类

Java
我要回答