Search code examples
javascjpshadowing

Shadowing variables in methods


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).


Solution

  • When you call changeNumber(), the reference to example is copied and passed to the method. You change the value of number, which modifies the referenced object, then reasssign a new instance to myClass, which does not affect the original reference in main.

    Everything goes as expected, then you exit the method. Back to the main method, you still have the primary reference to example, which was affected by the first reassignment (of number), but not by the reassignment of myClass. That's why you have 99, not the original 28.