引用与传递——内存分析

来源:互联网 发布:mac os x系统镜像 编辑:程序博客网 时间:2024/05/21 14:03

程序1:

class Demo{int temp = 30 ;// 此处为了方便,属性暂时不封装};public class RefDemo01{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值}};
图1图1
fun()方法执行完之后就断开连接,d2局部变量
程序2:
public class RefDemo02{public static void main(String args[]){String str1 = "hello" ;// 实例化字符串对象System.out.println("fun()方法调用之前:" + str1) ;fun(str1) ;// 调用fun()方法System.out.println("fun()方法调用之后:" + str1) ;}public static void fun(String str2){// 此处的方法由主方法直接调用str2 = "MLDN" ;// 修改字符串内容}};

图2 图2
【图1 与图2 的区别在于字符串内容的不可改变的特点,只是改变连接的内存】
程序3
class Demo{String temp = "hello" ;// 此处为了方便,属性暂时不封装};public class RefDemo03{public static void main(String args[]){Demo d1 = new Demo() ;// 实例化Demo对象,实例化之后里面的temp=30 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 = "MLDN";// 修改temp值}};

图3图3

【程序1和程序3流程上是一样的】

                                             
0 0