关于java中 对象的参数传递过程中,确实有些烦乱,在这里做一下总结:首先是一段测试代码
public class Main {
public class AA{
public String i;
public int j;
}
public static void main(String args[]) {
//System.out.print("dddaaass");
Main main=new Main();
main.test();
}
public void test(){
AA a=new AA();
a.i="a";
//测试参数中的 引用传递
System.out.print("before change the a.i is :"+a.i+"\n");
AA b=change(a);
System.out.print("after change the a.i is :"+a.i+"\n");
//测试参数返回时候的 传递方式
b.i="b";
System.out.print("after b change the a.i is :"+a.i+"\n");
//测试 对象 赋值时候的 赋值方式
AA c=new AA();
c=change(a);
c.i="c";
System.out.print("after c change the a.i is :"+a.i+"\n");
AA d=new AA();
d=c;
d.i="d";
System.out.print("after d change the a.i is :"+a.i+"\n");
//测试对象 值赋值的传递方式
AA g=new AA();
g.i="g";
System.out.print("the g.i is :"+g.i+"\n");
AA h=new AA();
h.i=g.i;
h.i="h";
System.out.print("after h change the g.i is :"+g.i+"\n");
}
public AA change(AA aa)
{
aa.i="Ca";
return aa;
}
}
通过上面的测试代码测试发现以下规律:
1.对象作为函数的参数传递过去的时候,是以原对象的引用的方式传递的,更改参数对象的值,会影响原来的对象。
2.对象作为函数的返回值的时候,传递过来的也是一个引用传递,更改传递过来的对象的时候,会影响原来的对象
3.对象A给另一个对象B赋值的时候(无论B是否经过了new 开辟新空间),此时的B是对A对象的一个引用,更改B会影响A
4.唯一的不是引用传递的方式是: 使用 基本数据类型赋值的方式,来对对象进行拷贝比如上例中的最后一种方式。这样出现的对象是一个新对象,不是原始对象的引用
补充:
1. java中的String类型虽然也为一个对象,但是在赋值传递的时候,走的是值传递的路线,和一般数据类型是同样的。String为一个特例。
总结: 对象的传递过程中, 基本上都是以引用传递来进行的,唯一的非引用传递的方法是: 自己开辟新的对象空间后,使用基本数据类型赋值方法(也可以自己实现一个copy复制函数)。