This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
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.