This gif was retrieved from https://blog.penjee.com/passing-by-value-vs-by-reference-java-graphical/
Maybe I'm terribly misunderstanding this, but please bear with me.
According to my understanding, when we define a variable in java, we are essentially creating a pointer to that object that is created. i.e.
Object objPointer = new Object();
Here objPointer is reference to the Object that was created, not the object itself. And when we use this object as an argument in a method:
void foo(Object newPointer){
//newPointer points to a copy of the Object objPointer pointed to.
}
foo(objPointer);
The formal argument newPointer is pointer to a copy of the value of the object that is passed as an argument. This is why swap methods don't work in java.
But my question is this: If the formal argument only points to a copy of the original object, then why can we change the values of the properties of that object? i.e.
class Object{
int var = 0; //default value of 0
void setVar(int newValue){
this.var = newValue;
}
}
void foo(Object newPointer){
newPointer.setVar(1);
}
Object objPointer = new Object();
//The Object objPointer points to has a var value of 0 as default.
foo(objPointer);
/*
After foo is called, the var value of objPointer has changed to 1
although the setVar method should only change the value of var for the copy
of that object that newPointer points to.
*/
I hope what I'm asking makes sense, the gif I found kind of illustrates what I'm saying: How are the properties of the cup Object changed, if fillCup only changes the properties of the copy?