Reputation: 37
I'm a beginner and I have a question about building objects.
I don't understand how it is possible to create two objects with the same variable name "oneCar" in this situation :
for (int i = 0; i<2 ; ++i)
{
Car oneCar = new Car();
}
It will create two objects "oneCar" with two different references.
But if I do this :
Car oneCar = new Car();
Car oneCar = new Car();
This will tell me that there is a duplicate variable.
Upvotes: 1
Views: 2046
Reputation: 59240
With a couple of exceptions, local variables in Java are scoped to the nearest surrounding set of braces. That means, as far as the compiler is concerned, the variable no longer exists once you exit the braces. The variable oneCar
declared on the first iteration doesn't exist by the time you reach the second iteration. It is equivalent to writing:
{
Car oneCar = new Car();
}
{
Car oneCar = new Car();
}
which is perfectly legal.
Upvotes: 4
Reputation: 21
Yes because you are declaring 2 time the same variable with the same name. I think you can solve your problem creating an array of Carand then use the constructor for each array field inside a for statement.
Car cars[10];
for(int i=0;i<9;i++){
cars[i]= new Car();
}
Upvotes: 2