I'm testing the result of this code, to realise how the static object creating works. Basically i understood everything till the last System.out.println(" " + a[0]); I ran the debugger, and i verified that in that point, all of the elements of the array have the same value on num variable. Can anyone explain me why is it happen?
static class Numero {
private static int sn = 0;
private int num;
public Numero(int n) {
num = n;
++sn;
}
public void setNum(int n) {
num = n;
}
public String toString() {
return "num = " + num + " sn = " + sn;
}
}
public static void main(String[] args) {
Numero[] a = new Numero[3];
Numero x = new Numero(12);
for (int i = 0; i < a.length; i++) {
a[i] = x;
a[i].setNum(i);
System.out.println(" " + a[i]);
}
System.out.println(" " + a[0]);
}
Output:
num = 0 sn = 1
num = 1 sn = 1
num = 2 sn = 1
num = 2 sn = 1