Java is JUST PASS-BY-VALUE.
In your case, imagine we got a class TV:
public class Tv {
boolean on;
int channel;
String model;
Tv (String model) {
this.model = model;
}
public void turnOn(){
this.on = true;
}
}
so now we order a Tv on amazon - have patience and wait 4-5 Days.
meanwhile we buy JUST a remote Control for our Tv. Since there is
no Tv there to control,we can play with our remote control, but
nothing will happen. In Java you would say "create a reference rcTv, which
refers to a Tv.
Tv rcTv; // our Tv remote control
still there is no Tv there to control. Now door is knocking, Yippee! our Tv is there.
In java you say you have now an instance of Tv.
new Tv(loewe) // create an instance of an TV-Object
but what is the purpose of a Tv if you cannot control it (turn it on/off...)!!!
Now we have to assign our remote control to our tv.
in java you say reffering to an instance of an object
rcTv = new Tv(loewe); // make rcTv to refer to our Tv-Object
you can even have another remote control
Tv rcTv2 // new Remote control (reference)
an assign it (copy) the value of our previous remote control
rcTv2 = rcTv; // make rcTv2 to control the same Tv as rcTv
now both of them are referring to the same Tv model Loewe.
We write a method to change the model of a Tv.
Tv changeModel (Tv tvarg, String model){
return tvarg = new Tv(model);
}
create third remote control referring to the same tv like the two others
Tv rcTv3 = rcTv; // create another Tv remote-control
now you can cotnrol your Loewe-Tv with all three RCs.
change the model of the last RC.
rcTV3 = changeModel (rcTv, "samsung")
you could assume after this call rcTv will refer to a new Tv-Instance (samsung).
BUT as mentioned above JAVA -> JUST PASS BY-VALUE
The point is you gave the method a reference (for c/c++-Folk a pointer) which can
referring to an TV-Object.
as long as JAVA IS JUST PASS BY VALUES, your reference (rcTV) is copied
into the method argument (tvarg) (read cloning your rcTv to tvarg).
Now both of them will refer to the same Tv -> Loewe
But after
tvarg = new Tv(samsung);
you have created a new TV-object and simultaneously you force tvarg now
to refer to that Tv-object and return it back.
So after
rcTV3 = changeModel (rcTv, "samsung")
your rcTv will still refer to Tv-Loewe and your rcTv3 will refer to Tv-Samsung.
regards