为什么我可以在循环中创建具有相同名称的多个实例? [英] Why can I create multiple instances with the same name in a loop?

查看:156
本文介绍了为什么我可以在循环中创建具有相同名称的多个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这个工作,我希望有人能解释给我。
这里是一个例子:

$ $ $ $ $ $ $ $ TestObject array [] = new TestObject [10];
for(int i = 0; i <= 10; i ++){
TestObject object = new TestObject();

object.setValue(i);
array [i] = object;
System.out.println(array [i] .getObject());





$ b为什么我可以创建多个具有相同名称的TestObject循环?
通常您不能创建具有相同名称的实例:

  TestObject o = new TestObject(1); 
TestObject o = new TestObject(2);

好的,这显然会引发错误...

循环,的作用域限于迭代。因此,在每次迭代中创建和销毁 TestObject对象


I don't understand why this works and I hope somebody can explain it to me. Here is an example:

TestObject array[] = new TestObject[10];
for(int i= 0; i <= 10; i++){
    TestObject object = new TestObject();

     object.setValue(i);
     array[i] = object;
    System.out.println(array[i].getObject());
}

Why can I create multiple instances of "TestObject" with the same name in the loop? Usually you can't create instances with the same name:

TestObject o = new TestObject(1);
TestObject o = new TestObject(2);

Well, this will obviously throws an error...

解决方案

The scope for a for loop is limited to the iteration. So TestObject object is created and destroyed in each iteration.

这篇关于为什么我可以在循环中创建具有相同名称的多个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆