I was reading the certification book of Java 6. And there was an example about “Shadowing variables”:
package scjp;
class Class1 {
int number = 28;
}
public class Example {
Class1 myClass = new Class1();
void changeNumber( Class1 myClass ) {
myClass.number = 99;
System.out.println("myClass.number in method : " + myClass.number);
myClass = new Class1();
myClass.number = 420;
System.out.println("myClass.number in method is now : " + myClass.number);
}
public static void main(String[] args) {
Example example = new Example();
System.out.println("myClass.number is : " + example.myClass.number );
example.changeNumber( example.myClass );
System.out.println("After method, myClass.number is : " + example.myClass.number);
}
}
And this is the result :
myClass.number is : 28
myClass.number in method : 99
myClass.number in method is now : 420
After method, myClass.number is : 99
My question is:
If at the beginning, the variable ‘number’ is 28. When I use the method, it changes the variable to 99 and 420. But …, when the method finish, why does the variable ‘number’ have a value of 99 instead of 28 ?
I thought it would have its original value (28).
When you call
changeNumber(), the reference toexampleis copied and passed to the method. You change the value ofnumber, which modifies the referenced object, then reasssign a new instance tomyClass, which does not affect the original reference inmain.Everything goes as expected, then you exit the method. Back to the
mainmethod, you still have the primary reference toexample, which was affected by the first reassignment (ofnumber), but not by the reassignment ofmyClass. That’s why you have 99, not the original 28.