淺談Java中的“指針”——引用

class TestReferenceandValue 
{
	private void test(int a){  
	   a = 10;
	}  

	public static void main(String[] args) {  
		TestReferenceandValue tav = new TestReferenceandValue();  
		int a = 3;  
		tav.test(a); //這裏傳遞的參數a就是按值傳遞  
		System.out.println(a); 
	}  
} 

Console:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

class TestReferenceandValue 
{
	private static void test(int a){  
	   a = 10;
	}  

	public static void main(String[] args) {  

		int a = 3;  
		test(a);
		System.out.println(a); 
	}  
} 

Console:

 

關於以上兩段代碼,想談的知識點有2點:

1. 兩段代碼相比較結合着看想說明:Java中靜態方法中只能調用靜態成員(靜態成員包括:靜態方法和靜態屬性)

如果想在靜態方法中調用非靜態成員,必須先將包含該非靜態承運的類,實例化後,再進行調用。

∵ 靜態成員從屬於類,而非靜態成員從屬於對象。

2. 只看其中任意一段代碼想說明:爲什麼a從始至終值都是3?

答:按值傳遞重要特點:傳遞的是值的拷貝,也就是說傳遞後對“值的拷貝”所進行的任何操作,都不影響“原值”。

即:tav.test(a); 這行代碼,是對a的拷貝所進行的,與原a無關,所以a仍爲3.

       按引用傳遞的重要特點:傳遞的是值的引用,也就是說傳遞前和傳遞後都指向同一個引用(也就是同一個內存空間)。

public class TestReferenceandValue  {  

	public static void test1(A a){  
		a.age = 20;  
    }  

	public static void main(String[] args) {  
		TestReferenceandValue  t = new TestReferenceandValue ();  
		A a = new A();   
		System.out.println(a.age);
		t.test1(a);  
		System.out.println(a.age);  
	}  

	public static class A{  
		public int age = 5;  
	}
}

Console:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章