“用对象来生成对象”“对象作为参数进行传递”“构造方法中的参数为对象”问题
本质上是“传值”与“传址”的问题
先说结论:
1、基本类型(包括String类)作为参数传递时,是传递值的拷贝,无论你怎么改变这个拷贝,原值是不会改变的
2、引用类型(包括数组,对象以及接口)作为参数传递时,是把对象在内存中的地址拷贝了一份传给了参数。
3、注意:基本数据类型的封装类Integer、Short、Float、Double、Long、Boolean、Byte、Character虽然是引用类型,但它们在作为参数传递时,也和基本数据类型一样,是值传递。Java - [参数传递] - 传值还是传地址?(引用)blog.csdn.net
例:
package thread;
public class Test2 {
public static void main(String[] args) {
int a = 3;
First first = new First();
first.print(a);
System.out.println("main中的a:"+a);
}
}
class First {
public void print(int a){
for(int i=0; i<5; i++){
a++;
}
System.out.println(a);
}
}
在这里,main中的a是实参,First中的a是形参,它们之间是两个地址,First中a的改变并不影响mian中的a。
package thread;
public class Test {
public static void main(String[] args) {
One2 one = new One2();
One2 one2 = new One2();
Tow2 tow = new Tow2();
one.print(tow);
one2.print(tow);
System.out.println(tow.sum);
}
}
class One2 {
public void print(Tow2 tow){
tow.print();
}
}
class Tow2 {
int sum = 0;
public void print(){
for(int i=0; i<5; i++){
sum++;
}
System.out.println(sum);
}
}
在这里,main中的tow是实参,One2中的tow是形参,它们之间是一个地址,两者的改变互相影响。