JAVA基础学习之路(十一)引用传递
引用传递:
不同栈内存可以指向同一块堆内存,不同栈内存可以对一块堆内存进行修改
范例一:
class Message { private int num = 10; public Message(int num) { this.num = num; } public void setNum(int num) { this.num = num; } public int getNum() { return this.num; } } public class test1 { public static void main(String args[]) { Message msg = new Message(30); fun(msg);//引用传递 System.out.println(msg.getNum()); } public static void fun(Message temp) { temp.setNum(100); } } //输出 100
内存分析:
范例二:
public class test1 { public static void main(String args[]) { String msg = "hello"; fun(msg);//引用传递 System.out.println(msg); } public static void fun(String temp) { temp = "world"; } }//输出:hello
输出结果仍为hello,msg的值没有被改变
原因:String类对象的内容一旦声明,则不可改变。对象内容的改变,依靠的是引用地址的改变
范例三:
class Message { private String info = "nihao"; public Message(String info) { this.info = info; } public void setInfo(String info) { this.info = info; } public String getInfo() { return this.info ; } } public class test1 { public static void main(String args[]) { Message msg = new Message("hello"); fun(msg);//引用传递 System.out.println(msg.getInfo()); } public static void fun(Message temp) { temp.setInfo("world"); } }//输出world
内存分析:
class Member { private int mid; private String name; private Member child; private Car car; public Member(int mid, String name) { this.mid = mid; this.name = name; } public String getInfo() { return "编号:"+this.mid+"\n"+ "名字"+this.name; } public void setCar(Car car) { this.car = car; } public Car getCar() { return this.car; } public void setChild(Member child) { this.child = child; } public Member getChild() { return this.child; } } class Car { private Member member; private String name; public Car(String name) { this.name = name; } public String getInfo() { return "车的名字"+name; } public void setMember(Member member) { this.member = member; } public Member getMember() { return this.member; } } public class test1 { public static void main(String args[]) { Member m = new Member(1,"张三"); Member ch = new Member(2,"李四"); Car c = new Car("宝马"); Car cc = new Car("奔驰"); m.setCar(c); c.setMember(m); ch.setCar(cc); cc.setMember(ch); m.setChild(ch); System.out.println(m.getCar().getInfo()); System.out.println(c.getMember().getInfo()); System.out.println(m.getChild().getCar().getInfo()); } }