• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shadowing of reference variables

 
Vivek Alampally
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags the next time you post some code.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can see that the instance variable doesn't change by outputting its value :
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic