Why can I create multiple instances with the same name in a loop?

前端 未结 4 958
滥情空心
滥情空心 2021-01-28 05:39

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 <= 1         


        
相关标签:
4条回答
  • 2021-01-28 06:13

    Every iteration of a loop is a block and, as a block, has its own scope. You can achieve the same result by doing this:

    {
        int i = 0;
    }
    {
        int i = 1;
    }
    // etc
    
    0 讨论(0)
  • 2021-01-28 06:22

    it's the scope of object problem. every iteration has its scope let's say they are not the same object at all

    0 讨论(0)
  • 2021-01-28 06:23

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

    0 讨论(0)
  • 2021-01-28 06:29

    This is because 'object' is in visibility scope of current loop iteration, so for next iteration, there can be initialized a new one with the same name (other scope).

    0 讨论(0)
提交回复
热议问题