Passing object references
Hello again world.
The following two programs are almost identical.
Please excuse my consumption of space but it's the only way I could be confident of phrasing my question correctly.
The only significant difference between the two versions is the one-line body of the "change()" method.
So, given the following two classes:publicclass Mutt
{
private String name;
public Mutt(String passedName)
{
name = passedName;
}
publicvoid change(Mutt rover)
{
rover.name ="Snoopy";
}
publicvoid printStuff()
{
System.out.println(name);
}
publicstaticvoid main(String[] params)
{
Mutt mutt =new Mutt("ScoobyDoo");
mutt.printStuff();
mutt.change(mutt);
mutt.printStuff();
}
}
/*
Output:
ScoobyDoo
Snoopy
*/
and
publicclass Dog
{
private String name;
public Dog(String passedName)
{
name = passedName;
}
publicvoid change(Dog rover)
{
rover =new Dog("Snoopy");
}
publicvoid printStuff()
{
System.out.println(name);
}
publicstaticvoid main(String[] params)
{
Dog dog =new Dog("ScoobyDoo");
dog.printStuff();
dog.change(dog);
dog.printStuff();
}
}
/*
Output
ScoobyDoo
ScoobyDoo
*/
I understand that when I pass the "mutt" in the first version, "rover" holds a reference to the Mutt object being passed and the method changes the mutt's name.
However, in the second version, when I pass the "dog", why doesn't the reference to the Dog object being passed now point to the new Dog - "Snoopy"?
I suspect someone will say, " . . . because you're usingnew to create a new reference."
But isn't that new reference being assigned to the passed object?
I hope I've made my confusion clear.
Thank you one and all.
Ciao for now.

