引用傳遞在java中有重要作用這裏 講解三個範例:
範例一:
class Demo{
int temp=30;//此處爲了方便,不封裝
};
public class Test{
public static void main(String args[]){
Demo d1=new Demo();//實例化Demo對象,實例化之後temp=30
d1.temp= 50 ;//修改temp屬性的內容
System.out.println("fun()方法調用之前:"+d1.temp);
fun(d1);
System.out.println("fun()方法調用之後:"+d1.temp);
}
public static void fun(Demo d2){//此處的方法由主方法直接調用
d2.temp = 1000;//修改temp值
}
}
內存分析圖:範例二:
public class Test{
public static void main(String args[]){
String str1= "hello" ;
System.out.println("fun()方法調用之前: "+str1);
fun(str1);
System.out.println("fun()方法調用之後: "+str1);
}
public static void fun(String str2){//此處的方法由主方法直接調用
str2="world";//修改字符串內容
}
}
內存分析圖:
範例三:
class Demo{
String temp= "hello" ;
};
public class Test{
public static void main(String args[]){
Demo d1=new Demo();//實例化Demo對象,實例化後temp="hello"
d1.temp="world";//修改temp屬性內容
System.out.println("fun()方法調用之前: "+d1.temp);
fun(d1);
System.out.println("fun()方法調用之後: "+d1.temp);
}
public static void fun(Demo d2){//此處方法由主方法直接調用
d2.temp="!!!";//修改temp值
}
}
內存分析圖:
範例一與範例三的流程是完全一樣的,第二個範例比較特殊,因爲String類是一個特殊的類,其內容是不可改變的。