I was messing around with some sample code to check if I understood how objects behave when referring to one another when I stumbled upon this situation:
public class exampleClass {
int testInt;
exampleClass pointedObj;
public static void main(String args[]) {
exampleClass Obj1= new exampleClass();
exampleClass Obj2= new exampleClass();
exampleClass Obj3= new exampleClass();
Obj1.pointedObj= Obj3;
Obj2.pointedObj= Obj3;
Obj1.testInt= 1;
Obj2.testInt= 2;
Obj3.testInt= 3;
Obj3= Obj2;
System.out.println(Obj1.pointedObj.testInt);
System.out.println(Obj2.pointedObj.testInt);
System.out.println(Obj3.pointedObj.testInt);
System.out.println(Obj1.testInt);
System.out.println(Obj2.testInt);
System.out.println(Obj3.testInt);
}
}
I expected to see on the console:
2
2
2
1
2
2
But instead I get:
3
3
3
1
2
2
And it's driving me crazy. Why does the pointed objects still hold the value "3" if none of the objects holds said value? I'm sure there is a similar question around, but I don't have the power to search for something this specific.
I'm already grateful for any help.
CodePudding user response:
The actual "value" stored in any object variable is a reference to an object, not the object itself. When you assign the value of one such variable to another, you are assigning that reference.
Let's walk through the code.
First you create three objects. Let's call the actual objects A, B, and C. You assign references to those objects to the variables.
exampleClass Obj1= new exampleClass(); // reference to object A
exampleClass Obj2= new exampleClass(); // reference to object B
exampleClass Obj3= new exampleClass(); // reference to object C
Then you make some assignments. Here you are taking the reference stored in Obj3
and storing it in some instance members.
Obj1.pointedObj= Obj3; // Object A's pointedObj now points to object C
Obj2.pointedObj= Obj3; // Object B's pointedObj now points to object C
Then you make some assignments to another instance member.
Obj1.testInt= 1; // Object A's testInt is now 1
Obj2.testInt= 2; // Object B's testInt is now 2
Obj3.testInt= 3; // Object C's testInt is now 3
Finally, you assign Obj2
to Obj3
. So Obj3
now points to object B. But this does not change what you previously assigned to the pointedObj
members. They still contain references to objectC.
Obj3= Obj2;