Java中的值传递和引用传递实例介绍
程序员文章站
2023-12-18 15:54:40
复制代码 代码如下:package object.reference; public class people { private s...
复制代码 代码如下:
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 中的值传递和引用传递
//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对象内容改变
}
}