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.

[3550 byte] By [SkupperJack] at [2007-9-30 19:41:28]
# 1

In both cases, a copy is made of the caller's reference, and that copy is passed. (This is pass-by-value, not pass-by-reference. Let the annoying sniping begin yet again.)

The new operator has nothing to do with any difference you think you are seeing.

I say "think" because it's NOT the case that the first one is changing the caller's value and the second one isn't.

The real difference is that the first one does rover.name = and the second one does rover = .

Because Java is 100% pure pass-by-value, doing rover = can never change what the caller sees. This is because the caller and the callee each have their own copy of the reference. Changing one to point at a different object (or to point at nothing by assigning null) does not change what the other points at.

However, while caller and callee have separate copies of the reference, both references point at the same object, so when you use rover.name = to change the state of that single object that both point at, both see the results.

jverd at 2007-7-7 0:26:05 > top of Java-index,Security,Event Handling...
# 2
> Let the annoying sniping begin yet again.Let 'em indeed.I'm good.Thanx.
SkupperJack at 2007-7-7 0:26:05 > top of Java-index,Security,Event Handling...