1. 程式人生 > >Java學習筆記之物件傳值和引用總結

Java學習筆記之物件傳值和引用總結

<strong><span style="font-size:18px;">
public class Test {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Circle c1 = new Circle(1);
		Circle c2 = new Circle(2);
		
		swap1(c1,c2);
		System.out.println("After swap1 : c1 = " + c1.radius + " c2 = " + c2.radius);
		
		
		swap2(c1,c2);
		System.out.println("After swap2 : c1 = " + c1.radius + " c2 = " + c2.radius);
	}
	
	public static void swap1(Circle x,Circle y) {
		Circle temp = x;
		x = y;
		y = temp;
		System.out.println("After swap1 : x = " + x.radius + " y = " + y.radius);
	}
	
	public static void swap2(Circle x,Circle y) {
		double temp = x.radius;
		x.radius = y.radius;
		y.radius = temp;
	}
}

class Circle {
	double radius;
	
	Circle(double newRadius) {
		radius = newRadius;
	}
}</span></strong>
輸出:
After swap1 : x = 2.0 y = 1.0
After swap1 : c1 = 1.0 c2 = 2.0

After swap2 : c1 = 2.0 c2 = 1.0

從swap1方法中輸出中可以看到x和y物件確實是調換了,但在主方法中顯示c1和c2是沒有調換的,為什麼呢?我們知道,想方法中傳遞物件實際傳送的是物件的引用,也就是x是c1的引用,y是c2的引用,但是x和c1是不同的引用,因為引用也是一種資料型別,它們也有存放地址,因此x和y調換後,對c1和c2是沒有影響的。

再來看看swap2方法,前面說了向方法傳遞物件時實際上是傳遞物件的引用,物件的資料域在方法中改變了,那麼在main方法中原物件的資料域也自然就改變了。

再舉一個簡單例子:

import java.util.Date;

public class Test {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Date date = new Date(1234567);
		System.out.println("Before m1 : " + date);
		m1(date);
		System.out.println("After m1 : " + date);
	
	}
	
	public static void m1(Date date) {
		date = new Date(7654321);
	}
}
輸出:

Before m1 : Thu Jan 01 08:20:34 GMT+08:00 1970
After m1 : Thu Jan 01 08:20:34 GMT+08:00 1970