I’m new to Java (honestly programming altogether), and have been testing out some stuffs.
I defined a class (say Nest), in which the class is defined by another class (say Nested), and the "Nested" class saves a variable(say a). So a "Nest" class saves a nested class, which saves a variable.
I needed multiple objects of the class Nest, so I defined an array of Nests, tried to modify only nest[0].nested.a, and not nest[i].nested.a. However, it turns out all the other objects that belong to this array’s varibales have also been modified.
This is what I tried:
class Test{
public static class Nested{
static int a;
Nested(int a){
this.a = a;
}
}
public static class Nest{
Nest nested;
Nest(Nested nested){
this.nested = nested;
}
}
public static void main(String [] args){
Nest [] nest = new Nest[2];
Nested nested = new Nested(0);
nest[0] = new Nest(nested); //nest[0].nested.a = 0
nest[1] = new Nest(nested); //nest[1].nested.a = 0
System.out.println(nest[0].nested.a + "\t" + nest[1].nested.a);
nest[0].nested.a = 1;
//Also tried nest[0].nested = new Nested(1); but didn't make a difference
System.out.println(nest[0].nested.a + "\t" + nest[1].nested.a);
}
}
Expectations were:
0 0
1 0
But got the results:
0 0
1 1
Would there be a way to get the expected results while keeping the array? Thanks.
>Solution :
The issue is that both Nest
classes have references to the same Nested
instance. To get the behavior you want, you should create two Nested
instances, one for each Nest
array element.