Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

shadowing reference variable

 
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all
i didn't get the concept of shadowing reference variable

i confused with the things that happens in the line 1 and 2.




class Bar {
int barNum = 28;
}
class Foo {
Bar myBar = new Bar();
void changeIt(Bar myBar) {
myBar.barNum = 99;
System.out.println("myBar.barNum in changeIt is " + barNum);//1
myBar = new Bar();
myBar.barNum = 420;
System.out.println("myBar.barNum in changeIt is now " + barNum);//2
}
public static void main (String [] args) {
Foo f = new Foo();
System.out.println("f.myBar.barNum is " + f.myBar.barNum);
changeIt(f.myBar);
System.out.println("myBar.barNum after changeIt is " + f.myBar.barNum);
}
}

o/p

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

anyone please....
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
its simple concept of local vs. global scope of variables in this example.

but of course, in line 1 and 2, there is an error...

System.out.println("myBar.barNum in changeIt is " + barNum);//1
System.out.println("myBar.barNum in changeIt is now " + barNum);//2

barNum can't be accessed as barNum, it has to be myBar.barNum
So along with these 2 statements, if you print this.myBar.barNum, your confusion will go off
 
This parrot is no more. It has ceased to be. Now it's a tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic