电脑技术学习

Java的pass by Value(传值)

dn001
内容: Java中使用“pass by value"函数调用 方式,这常常造成许多人迷惑。在所有地点,Java都使用严格采用pass by value,所以下列程序:
 class Param {
public static void main (String [] args){
int x = 3;
triple(x);
System.out.println("x after triple : "+ x);
}
private static void triple (int arg)
{
arg = arg * 3;
System.out.println("arg in triple :"+ arg);
}
}


会产生这样的输出:
arg in triple : 15
x after triple : 5

这段代码不致于让人糊涂。但如果参数中传递的是对象,可能把人弄迷糊了。
如果在程序中以Date对象表示日期,那么下列程序:
class Param {
public static void main (String [] args){
Date d1 = new Date("1 Apr 98");
nextDateUpdate(d1);
System.out.println("d1 after nextDay: " + d1);

Date d2 = new Date("1 Apr 98");
nextDateReplace(d2);
System.out.println("d2 after nextDay: " + d2);
}
private static void nextDateUpdate (Date arg) {
arg.setDate( arg.getDate() + 1);
System.out.println("arg in nextDay : " + arg);
}
private static void nextDateReplace (Date arg) {
arg = new Date(arg.getYear(),arg.getMonth(),arg.getDate()+1);
System.out.println("arg in nextDay : " + arg);
}
}


产生的输出:

arg in nextDay : Thu Apr 02 00:00:00 CST 1998
d1 after nextDay: Thu Apr 02 00:00:00 CST 1998
arg in nextDay : Thu Apr 02 00:00:00 CST 1998
d2 after nextDay: Wed Apr 01 00:00:00 CST 1998

从本质上说,object reference 是按值传递的(pass by value)。因此可以修改参数对象的内部状态,但参数对象重新赋值,没有意义。

Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd Java中使用“pass by value"函数调用 方式,这常常造成许多人迷惑。在所有地点,Java都使用严格采用pass by value,所以下列程序:
  class Param {
public static void main (Strin

标签: