Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Can someone talk about the reference?  RSS feed

Simon Sun
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi pals,
I pop up the question about Madhu's code.
I borrow his code, hope he won't mind.
Button btn;
btn=new Button("Good");
public void replacer(Button replaceMe){
replaceMe=new Button("Evil");
/******output is Good
TextField tf;
tf=new TextField("Yin");
public void changer(TextField changeMe){
/*****output is Yang
My question is what the reference exactly is? As I understand it,
it refer the address of memory. some experts say that when we pass object in the arguments, we pass the copy of reference.
I am confused. the copy of reference is still pointing to the same memory location. so we change it, we change both.
So the both cases above should been changed.
Hope someone can throw me a light.
I really like this web site.
Madhav Lakkapragada
Ranch Hand
Posts: 5040
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a reference is just a pointer to the Object.
The Object lies somewhere in memory.
The closest analogy I can give is say Object is represented
like a City. A reference is the route you follow to get to
that City. Also, you should now realise that you can have
many routes to reach a City. Similarly, there can be many
references to an Object.
Having said that Object is a City and reference is a route, we see what is happening in the code abv:
Code 1:
btn route is created and it points to the
City GoodButton.
Then a call to the replacer() is made.
As you know, we will pass a copy of the
btn route to the function.
Now the function takes this replaceMe route
and points it to a new City Evil and returns.
However, please note that our original btn route and GoodButton City are not changed.
Code 2:
tf route is created and points to a City Yin.
Then we make call to the changer() function with a copy of the route calling the copied route as changeMe. Now since, route changeMe is a copy of route tf, it still points to the city Yin. Using this changeMe route, I reach the city Yin and change its name to Yang. So, now the Yin city name has changed to Yang. Then return.
After returning, we use the route tf to goto the city. And to our surprise find that the name of the city has changed from Yin to Yang, but still it is the same City.
All others, am I anywhere close.....
just imagining stuff.....pretty boring afternoon for me here, so trying to be creative.....
- satya

[This message has been edited by Madhav Lakkapragada (edited January 10, 2001).]
Carl Trusiak
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The campfire Story Pass by Value Please may help you understnad this
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!