java引用传递

1)应用传递就是指将对内存空间的使用权交给多个栈内存空间。

2)对象的引用传递

 1 class Demo{
 2     int temp = 30;
 3 }
 4 
 5 public class TestJava0583 {
 6 
 7     public static void main(String[] args) {
 8         Demo d1 = new Demo();
 9         d1.temp = 50;
10         System.out.println("调用之前" + d1.temp);
11         fun(d1);
12         System.out.println("调用之后" + d1.temp);
13         
14     }
15     public static void fun(Demo d2){
16         d2.temp = 1000;
17     }
18 
19 }

输出结果为:

调用之前50
调用之后1000

 

分析:调用fun()方法时,d2指向了主函数中new出的对象空间,且用d2修改了此空间的内容,执行fun()方法完毕后,该指向消失。

3)String类型变量的引用传递

 1 public class RefDemo02 {
 2 
 3     public static void main(String[] args) {
 4         String str1 = "hello";
 5         System.out.println("fun方法调用之前" + str1);
 6         fun(str1);
 7         System.out.println("fun方法调用之后"+ str1);
 8     }
 9     public static void fun(String str2){
10         str2 = "zhangsan";
11     }
12 
13 }

输出结果为:

fun方法调用之前hello
fun方法调用之后hello

 

分析:字符串的内容一旦声明是不可改变的,改变的只是其内存地址的指向。调用fun()方法使str2指向str1所指空间,但是执行str2 = “zhangsan”时,str2的指向不再是str1所指的空间,而是指向另一个空间,将“zhangsan”内容放入其中。

整个过程中,str2不会影响str1所指空间中的内容。

4)String作为类的一个属性存在时:

 1 class M{
 2     String temp = "hello";
 3 }
 4 
 5 public class RefDemo03 {
 6 
 7     public static void main(String[] args) {
 8         M d1 = new M();
 9         d1.temp = "world";
10         System.out.println("fun方法之前" + d1.temp);
11         fun(d1);
12         System.out.println("fun方法之后" + d1.temp);
13     }
14     public static void fun(M d2){
15         d2.temp = "zhangsan";
16     }
17 
18 }

输出结果为:

fun方法之前world
fun方法之后zhangsan

 

分析:本程序的分析方法和2)中的分析方法一样,因为String时作为类的属性存在的,而在操作时更改的只时类中的属性内容。

 

posted @ 2017-07-25 11:33  XuGuobao  阅读(301)  评论(0编辑  收藏  举报