作者:优雅de禽兽 | 来源:互联网 | 2022-02-04 13:57
代码如下:
package Object.reference;
public class People {
private String name;
private int age;
public People(){
}
public People(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString(){
return "name:" + name + " age:" + age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
代码如下:
package Object.reference;
/* java 中的值传递和引用传递
https://www.jb51.net/clara/archive/2011/09/17/2179493.html
java 中没有引用传递,都是值传递的
*/
public class Test {
public static void swap(People a, People b, boolean flag) {
if (flag) {
// 可以通过传递副本修改对象的值
a.setName("changeName");
a.setAge(100);
} else {
//副本交换,并不影响主程序的指针
People c = a;
a = b;
b = c;
}
}
public static void main(String[] args) {
People p1 = new People("yingjie", 23);
People p2 = new People("yuexin", 20);
swap(p1, p2,false);//传递的是p1,p2的副本,函数调用前后p1,p2没任何改变
swap(p1, p2,true);//传递的是p1,p2的副本,可以通过传递副本修改对象的值,函数调用前后p1对象内容改变
}
}