void foo(Dog newDog){
newDog.name.equals("FOO"); //true
newDog = new Dog("FIFI"); // create a new DOG object mem location 72. my doubt here
newDog.name.equals("FIFI"); //true
}
Here newDog
is a local variable to that method. When you call that method and pass someDog
, the value of someDog
(which is a reference to a Dog
object) is copied into newDog
. So now you have 2 references pointing to the same object. That's why the first line evaluates to true
.
After you execute
newDog = new Dog("FIFI");
the variable newDog
references the newly created Dog
object. This does not change the variable someDog
at all. So now, you have 2 variables, each pointing to a different Dog
object.
After the method is done, the newDog
variable disappears, and the newly created Dog
object has no more reference pointing to it, so it becomes eligible for garbage collection.
The code posted in the method doesnt't change any attributes of the object referenced by someDog
, and it can never switch the object referenced by someDog
That's why
someDog.setName("FIFI"); // is false
Understood?