不一樣棧內存能夠指向同一塊堆內存,不一樣棧內存能夠對一塊堆內存進行修改this
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的值沒有被改變spa
緣由:String類對象的內容一旦聲明,則不可改變。對象內容的改變,依靠的是引用地址的改變code
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()); } }