引用傳遞的核心意義:java
同一塊堆內存空間能夠被不一樣的棧內存所指向,不一樣的棧內存能夠對同一個堆內存進行內容的修改。this
實例1:spa
class Message { private int num = 10; public Message(int num){ this.num = num; //2.this是表明msg這個對象,num = 30 } public void setNum(int num){ this.num = num; } public int getNum(){ return this.num; } } public class Demo{ public static void main(String args[]){ Message msg = new Message(30); //1.實例化Massage對象msg fun(msg); //3.調用fun方法 System.out.println(msg.getNum()); } public static void fun(Message temp){ temp.setNum(100); //4.temp是msg,調用Massage類的setNum方法,num=100 } } /*-------------------------------------------------------------- E:\Javacode>java Demo 100 E:\Javacode>*/
實例2:code
public class Demo{ public static void main(String args[]){ String msg = "hello"; fun(msg); System.out.println(msg); } public static void fun(String temp){ temp = "World"; } } /*---------------------------------------------- E:\Javacode>java Demo hello E:\Javacode>*/
實例3:對象
class Message { private String info = "你好"; public Message(String info){ this.info = info; } public void setInfo(String info){ this.info = info; } public String getInfo(){ return this.info; } } public class Demo{ 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"); } } /*------------------------------------------ E:\Javacode>java Demo world E:\Javacode>*/