1.引用传递
1.1 范例
class Ref1{
int temp = 10;
}
public class RefDemo01 {
public static void main(String args[]){
Ref1 r1 = new Ref1();
r1.temp = 20;
System.out.println(r1.temp);
tell(r1);
System.out.println(r1.temp);
}
public static void tell(Ref1 r2){
r2.temp = 30;
}
}
public class RefDemo02 {
public static void main(String[] args){
String str1 = "hello";
System.out.println(str1);
tell(str1);
System.out.println(str1);
}
public static void tell(String str2){
str2 = "world";
}
}
**因为String类型的数据是不能更改的,所以str2的指向在tell(str1);
的作用下指向了hello
**
1.3 范例
class Ref2{
String temp = "hello";
}
public class RefDemo03 {
public static void main(String[] args){
Ref2 r1 = new Ref2();
r1.temp = "world";
System.out.println(r1.temp);
tell(r1);
System.out.println(r1.temp);
}
public static void tell(Ref2 r2){
r2.temp = "xueyuan";
}
}
**r1首先是hello,接下来r1被改为world,其实是被开辟了一个新空间,他的指向也被断开,由原先指向hello变为指向world。创建了r2同样也执行world这个值,这样r2也开辟了一个新的空间,然后r2断开连接指向了xueyuan。
**