Dice x_i = new Dice(6); // if n = 3, the variables x_0, x_1 and x_2 will be created: 3 dices with 6 sides each
Offcourse instances with
names like x_0, x_1 and x_2 are not created here. But
Different instances are indeed created, each time having same name x_i (
there is no relation between 'i' in x_i and 'i' in for loop, so x_0, x_1, etc won't be created).
Here new Dice(6) will each time create new instances, so it serves the purpose as required by you.
For your better understanding try running below sample code and
see value of 'a' is different for each instance because they indeed different instances stored in ArrayList:
import java.util.ArrayList;
public class DiceCheck
{
public static void main(String[] args)
{
DiceN diceN = new DiceN(3);
diceN.showDices();
}
}
class Dice
{
int sides;
int a=0;
public Dice(int sides)
{
this.sides = sides;
}
public int getA()
{
return a;
}
public void setA(int a)
{
this.a = a;
}
}
class DiceN
{
ArrayList dices = new ArrayList();
public DiceN(int n)
{
for(int i=0;i<n;i++)
{
Dice x_i = new Dice(6);
x_i.setA(i);
dices.add(x_i);
}
}
public void showDices()
{
for(int i=0;i<dices.size();i++)
{
Dice x_i = (Dice)dices.get(i);
System.out.println(x_i.getA());
}
}
}