求指教public class Test {
int i = 1;
Dog d;
Test(){}
Test(int i) {
this.i = i;
}
Test(int i, String name) {
this.i = i;
this.d = new Dog(name);
}
public static void main(String[] args) {
Test t = new Test();
System.out.print(t.i + "\t");
setTest(t);
System.out.print(t.i + "\t");
setTest(t, 5);
System.out.print(t.i + "\n");
t = new Test(2, "ahuang");
System.out.println(t.d);
setDog(t.d);
System.out.println(t.d);
setDog(t);
System.out.println(t.d);
}
public static void setTest(Test t) {
t = new Test(3);
}
public static void setTest(Test t, int i) {
t.i = i;
}
public static void setDog(Dog d) {
d = new Dog("heizi");
}
public static void setDog(Test t) {
t.d = new Dog("heizi");
}
}class Dog {
int id;
static int count = 0;
String name;
Dog(String name) {
id = count++;
this.name = name;
}
public String toString() {
return this.id + "\t" + this.name;
}
}/*
* outPut:~
* 1 1 5
* 0 ahuang
* 0 ahuang
* 2 heizi
*/
int i = 1;
Dog d;
Test(){}
Test(int i) {
this.i = i;
}
Test(int i, String name) {
this.i = i;
this.d = new Dog(name);
}
public static void main(String[] args) {
Test t = new Test();
System.out.print(t.i + "\t");
setTest(t);
System.out.print(t.i + "\t");
setTest(t, 5);
System.out.print(t.i + "\n");
t = new Test(2, "ahuang");
System.out.println(t.d);
setDog(t.d);
System.out.println(t.d);
setDog(t);
System.out.println(t.d);
}
public static void setTest(Test t) {
t = new Test(3);
}
public static void setTest(Test t, int i) {
t.i = i;
}
public static void setDog(Dog d) {
d = new Dog("heizi");
}
public static void setDog(Test t) {
t.d = new Dog("heizi");
}
}class Dog {
int id;
static int count = 0;
String name;
Dog(String name) {
id = count++;
this.name = name;
}
public String toString() {
return this.id + "\t" + this.name;
}
}/*
* outPut:~
* 1 1 5
* 0 ahuang
* 0 ahuang
* 2 heizi
*/
不管是基本类型还是引用类型,都会传递其值或引用的副本到函数中去。
详情可以参考 《core java》第一卷的讲解
可以看看我贴出来的代码吗,看看比如说这个方法setDog(t);为什么我在方法中改变了参数的值,可是实际的值也变了。
对象的引用指向一块内存区域,该区域是该对象的实际数据.
你要把java里面的对象存储模型搞清楚才行。
但是事实和和你说的有一定区别,看看setTest(t);这个方法的,我之前也是你那么想的。
setTest(t)后不变t的值不变;
setTest(t, 5)后变了;
setDog(t.d)后不变;
setDog(t)后变了。
System.out.print(t.i + "\t");
setTest(t);// t 是引用传递可以改变对象的属性,但是引用本身并不会改变。
System.out.print(t.i + "\t");// = 1
setTest(t, 5);// t 的属性i 改变
System.out.print(t.i + "\n");//=5
t = new Test(2, "ahuang");
System.out.println(t.d);// Dog的id无值.=0
setDog(t.d);//setDog中 d = new Dog("heizi"); d 引用改变了。t.d的值没变。==0 ahuang
System.out.println(t.d);
setDog(t);//setDog(Test t)中修改的t 引用的属性 == heizi 为什么==2 heizi 是因为你前边setDog(Dog d) 的时候。count =1 了,所以现在是2
System.out.println(t.d);
setTest(t);// t 是引用传递可以改变对象的属性,但是引用本身并不会改变。 setDog(t.d);//setDog中 d = new Dog("heizi"); d 引用改变了。t.d的值没变。==0 ahuang这两句我没懂,在setTest(Test t)中我不是改变了t = new Test(3)了吗?
还有 public static void setDog(Dog d)中我也改变了d啊,d变成了新new出来的一只叫heizi的狗狗了噢,但是为什么却没变呢?