方法参数的调用是值调用而不是摘引调用

方法参数的调用是值调用而不是引用调用

方法参数的调用是值调用而不是引用调用




package com.ray.object;


/**
 * 方法参数的调用是值调用,而不是引用调用
 * 
 * @author ray
 * @since 2015-04-22
 * @version 1.0
 * 
 */
public class Person {

	private static void swap(Person a, Person b) {
		Person temp = a;
		a = b;
		System.out.println("a:" + a);
		b = temp;
		System.out.println("b:" + b);
	}

	public static void main(String[] args) throws Exception {
		Person bill = new Person();
		Person jack = new Person();
		System.out.println("--bill:" + bill);
		System.out.println("**jack:" + jack);
		Person.swap(bill, jack);
		System.out.println("--bill:" + bill);
		System.out.println("**jack:" + jack);
	}
}

输出:

--bill:com.ray.object.Person@1fb8ee3
**jack:com.ray.object.Person@61de33
a:com.ray.object.Person@61de33
b:com.ray.object.Person@1fb8ee3
--bill:com.ray.object.Person@1fb8ee3
**jack:com.ray.object.Person@61de33


从上面的输出结果可以看见,在swap方法里面,两个参数的确是已经调换了,但是由于参数是对象,所有调用的时候是值调用,而不是引用调用,

只不过参数返回的值变动了,但是相应的对象还是没有变,因此,最后的结果两个对象是没有调换过来