Reputation: 8857
Why doesn't this change the initial object:
public class Foo
{
Bar item = new Item(5);
public changeBar(Bar test){
test = new Item(4);
}
public run(){
changeBar(item);
}
}
In this case item
doesn't get changed. How is this possible? I mean, you're passing the reference as parameter in the method, so I'd say assigning a new value to it, means the initial item
would also be changed.
Can someone explain to me how this works.
=======================================
however, my question is the following:
the following does work right?
public changeBar2(Bar test){
test.parameter = "newValue";
}
I don't see how that's different.
Upvotes: 2
Views: 314
Reputation: 34625
public changeBar(Bar test){
test = new Item(4);
}
changeBar(item);
Here the value in item
in copied to test
. So as of now, both item, test
are pointing to same object(s). Inside the method, test
is pointing to a different location which doesn't affect the item
. You are passing by value and not by reference.
public changeBar2(Bar test){
test.parameter = "newValue";
}
The above modifies the object that is passed because both the test
and item
are referring to the same object.
So, test
can totally either point to a new object or modify the object was earlier referring to. Both are different and are valid.
Upvotes: 2
Reputation: 2795
You are giving the method the reference to this object, that is, its address so to speak. So this address is stocked in a variable named test
.
Then your method erases what is written in the test
variable, and writes instead the address of a new Item
object it created. Nothing here changes anything to the initial Item
object, nor to the references to it that are outside the method's scope.
I guess I am pretty approximative here and I will be glad to get corrected.
Upvotes: 0
Reputation: 30216
Parameters in Java are ALWAYS passed-by-value.
At the beginnning of function changeBar() test is a reference to item, but then you overwrite it with a reference to a newly created item. You therefore only overwrite the local variable with a different reference, but don't change the referenced by object.
Upvotes: 1
Reputation: 190925
test
in changeBar
is basically as pointer. So when you assign it, you are changing the pointer.
Here is an article: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
Upvotes: 0
Reputation: 992955
Consider a thought experiment:
changeBar(null);
Would your code above change the value of null
?
The answer to your question is that although your Bar
object is passed "by reference", this is different from passing the reference itself by value. In Java, all parameters are passed by value, even when they are themselves references to other objects.
Upvotes: 3