开发者

Java reference-type in parameter

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.


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.


 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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜