aspose file tools*
The moose likes Beginning Java and the fly likes Shadowing of reference variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Shadowing of reference variables" Watch "Shadowing of reference variables" New topic
Author

Shadowing of reference variables

Vivek Alampally
Ranch Hand

Joined: Jul 10, 2008
Posts: 67
Hello,

Kindly look at the following program and explain why the fourth line in output is 99 instead of 420

Output
-----------
f.myBar.barNum is 28
myBar.barNum in changeIt is 99
myBar.barNum in changeIt is now 420
f.myBar.barNum after changeIt is 99

Thanks
Vivek.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Please UseCodeTags the next time you post some code.


[My Blog]
All roads lead to JavaRanch
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

In changeIt, myBar = new Bar(); is assigning a new instance to the method parameter myBar, not to the instance variable. myBar.barNum = 99 sets the instance variable to 99, because the instance variable was passed to the method (i.e. method parameter = instance variable).
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

You can see that the instance variable doesn't change by outputting its value :
 
Consider Paul's rocket mass heater.
 
subject: Shadowing of reference variables