java ref传引用_java引用传递

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

2)对象的引用传递

1 classDemo{2 int temp = 30;3 }4

5 public classTestJava0583 {6

7 public static voidmain(String[] args) {8 Demo d1 = newDemo();9 d1.temp = 50;10 System.out.println("调用之前" +d1.temp);11 fun(d1);12 System.out.println("调用之后" +d1.temp);13

14 }15 public static voidfun(Demo d2){16 d2.temp = 1000;17 }18

19 }

输出结果为:

调用之前50

调用之后1000

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

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

1 public classRefDemo02 {2

3 public static voidmain(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 voidfun(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 classM{2 String temp = "hello";3 }4

5 public classRefDemo03 {6

7 public static voidmain(String[] args) {8 M d1 = newM();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 voidfun(M d2){15 d2.temp = "zhangsan";16 }17

18 }

输出结果为:

fun方法之前world

fun方法之后zhangsan

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值