【发布时间】:2016-09-22 09:01:21
【问题描述】:
您好,我有以下代码:
public class Dog {
private String name;
private int size;
public Dog(String name, int size){
this.name = name;
this.size = size;
}
public void changeSize(int newSize){
size = newSize;
}
public String toString(){
return ("My name "+name+" my size "+ size);
}
}
public class PlayWithDog {
public PlayWithDog(Dog dog){
dog = new Dog("Max", 12);
}
public void changeDogSize(int newSize, Dog dog){
dog.changeSize(newSize);
}
public static void main(String[] args){
Dog dog1 = new Dog("Charlie", 5);
PlayWithDog letsPlay = new PlayWithDog(dog1);
System.out.println(dog1.toString()); // does not print Max.. Prints Charlie... .. Does not change... WHYYY???
letsPlay.changeDogSize(8, dog1);
System.out.println(dog1.toString()); // passing by value.. Expected Result... changes the size
dog1 = new Dog("Max", 12);
System.out.println(dog1.toString()); // Expected result again.. prints Max
}
}
我知道 Java 总是按值传递所有内容。无论是原始类型还是对象。然而,在对象中,引用是传递的,这就是为什么您可以在对象通过方法传递之后对其进行修改的原因。我想测试当对象通过不同类的构造函数传递时是否同样适用。我发现对象没有改变。这对我来说似乎很奇怪,因为我只是在构造函数中传递对象的引用。它应该改变......?
【问题讨论】:
-
您没有更改(变异)作为参数传递的对象,而是更改(重新分配)构造函数中的变量。这一切都在副本中进行了解释。
标签: java object constructor pass-by-reference pass-by-value