posted 19 years ago
In the first method, we use "new" to create an object of the type ValHold1, referenced by the local variable v.
When we call another(v, i), we are passing a reference to that object. Method arguments are copies, and they are local to the method. So we now have a local variable v in the first method, and another local variable v in the second method. But although these are separate local variables, they both reference the same object (the one created with "new" above).
So when we invoke v.i=20 (using the reference copy in the second method), this sets i=20 in the object itself. So if the first method were to reference that object (with its own local variable v), the value of v.i will be 20.
After modifying the original instance of ValHold1, the second method also creates a new instance of ValHold1, referenced by vh. Then, it sets v=vh. This simply reassigns the local variable v in the second method, so that it references the newly created object instead of the original object.
Note, however, that this has no effect on the first method's local variable v, which still references the original object.
So... When the second method prints v.i, it is printing the value of i in the newly created instance (also referenced by vh), so this is 10. When the second method prints i, it prints the value of the local variable i, so this is 0. Then when the first method prints v.i, it is printing the value of i in the original instance, which is now 20 because the object itself was modified (by way of the reference passed to the second method).
[ December 14, 2004: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org