引用传递的核心意义:
同一块堆内存空间可以被不同的栈内存所指向,不同的栈内存可以对同一个堆内存进行内容的修改。
实例1:
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对象msgfun(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 100E:\Javacode>*/
实例2:
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 helloE:\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 worldE:\Javacode>*/