pass by value vs pass by reference

来源:互联网 发布:c语言 fprintf 编辑:程序博客网 时间:2024/04/30 04:09

pass by value

当参数是pass by value时,调用者和被调用者是有两个相同具有相同值的独立变量,被调用者修改了参数的值,调用者是看不到效果的。

pass by reference

当参数是pass by reference时,调用者和被调用者是使用一个相同的变量,如果调用者更改了参数的值,调用者是可以看到效果的。

Java参数传递

java都是pass by value, 看下面这个例子

public static void main(String[] args) {    String x = new String("ab");    change(x);    System.out.println(x);   //ab}public static void change(String x) {    x = "cd";}

这个例子和string的不可变性无关,只是因为Java是值传递

看另外一个例子

public static void main( String[] args ) {    Dog aDog = new Dog("Max");    foo(aDog);    // when foo(...) returns, the name of the dog has been changed to "Fifi"    aDog.getName().equals("Fifi"); // true}public static void foo(Dog d) {    d.getName().equals("Max"); // true    // this changes the name of d to be "Fifi"    d.setName("Fifi");}

这个表面一看看起来是传递的引用,实际上,Dog aDog是个变量,这个变量存储的是对象new Dog(“Max”)的地址,参数传递的时候传递的仍然是aDog的值,只是这个sDog的值又恰好是new Dog(“Max”)的地址而已。