Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shadow variable doubt

 
saipraneeth nallapareddy
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


most of the times with or without my knowledge i used this concept in my coding logic with the knowledge from C, but came to know the terminology for this particular concept is shadowing variable, ofcourse name doesn't matter what you get is important.

the output for the above piece of code is

but i felt the last line of the print statement must also give the value 420. ofcourse the output is not wrong the way i understand it is wrong can one please guide me the right way what actually going on there.
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Call By Reference vs Call By Value
 
saipraneeth nallapareddy
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the link, contains the info what i am looking for, cleared with issue.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<edit>Rob beat me!</edit>
saipraneeth nallapareddy wrote:


f.myBar.barNum after changeIt is 99
ofcourse the output is not wrong the way i understand it is wrong can one please guide me the right way what actually going on there.


well, the key concept here is when you pass a reference to a method as argument, *it is always pass by copy of the reference*. we will work on your first 4 line of your changeIt method


so in first statement, myBar[say localBar] is a separate copy reference , but still it point to the same Object[say Ranch] which is already pointed by instance variable of myBar[say instanceBar]. clear? .
now if you change the object with localBar as myBar.barNum it affect the Ranch object. so now comment (2) and (3) and test , you come to know.

back to the explanation, when you say myBar = new Bar() in (2) . here you reassign the localBar object into a newly created Object(say New, which has a default value for barNum = 28)
*careful, in this point instanceBar points existing Object called Ranch and localBar points New*, so changing the barNum with localBar wont affect Ranch instead it affect New.
thus, you dont see this change in your output.

is it clear?

hth

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic