Frage

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

War es hilfreich?

Lösung

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.

Andere Tipps

You change the value of the instance you treat to 99; afterwards you create a NEW instance and modify that.

The newly created instance is discarded at the end of changeNumber() because it is no longer referenced.

1- from first line the number =28:

Main example = new Main();///////Main call class1(myClass)---->which set number=28

2- System.out.println("myClass.number is : " + example.myClass.number );////the output here is (myClass.number is : 28)

3- example.changeNumber( example.myClass );///////in this method you will set number=99 then print it ( myClass.number in method : 99 ) , then creat new object( which mean the number=28 , and the number in previous object still =99), the new object (myClass = new Class1();) will print (myClass.number in method is now : 420)

4- System.out.println("After method, myClass.number is : " + example.myClass.number);///// this line will print (After method, myClass.number is : 99) because this is from the first object created (myClass)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top