这里写一下java的值传递
参数是基本类型的时候:
class param {
public static void main( String[] args ){
int x = -1 ;
change( x );
System.out.println("x = " + x );
}
public static void change( int x){
x = 10 ;
System.out.println("change(), x = " + x );
}
}
以上代码的结果大家应很清楚吧。
但是参数是对象的时候,可能就有点人迷糊了。
public class handleTitle {
public static void main(String[] args){
handleTitle.test t = new handleTitle().new test(1,1);
System.out.println(t.getX());
System.out.println(t.getY());
put(t);
System.out.println(t.getX());
System.out.println(t.getY());
}
public static void put( test t){
t.setX(5);
t.setY(6);
}
class test {
int x ;
int y ;
public test( int x , int y){
this.x = x;
this.y = y ;
}
public test(){
}
void setX(int xx){
x = xx;
}
int getX(){
return x;
}
void setY(int yy){
y = yy;
}
int getY(){
return y;
}
}
}
测试结果是:
1
1
5
6
从本质上来说,object reference是按值传递的,因此可以修改参数对象的内部状态,但是对参数对象重新赋值,没有意义