Java中的值傳遞和援用傳遞實例引見。本站提示廣大學習愛好者:(Java中的值傳遞和援用傳遞實例引見)文章只能為提供參考,不一定能成為您想要的結果。以下是Java中的值傳遞和援用傳遞實例引見正文
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 中的值傳遞和援用傳遞
http://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對象內容轉變
}
}