java对象在通过构造函数后不会更改。为什么?
嗨,我有以下代码:
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总是通过值传递一切。无论是基本类型还是对象。但是,在对象中,引用是传递的,这就是为什么在对象通过方法传递后可以修改对象的原因。我想测试当对象通过另一个类的构造函数时,是否同样适用。我发现这个对象没有被改变。这对我来说似乎很奇怪,因为我只是在构造函数中传递对象的引用。它应该改变
# 1 楼答案
这就是为什么构造函数对传入的对象不做任何处理。可以更改传入对象的状态,但不能更改原始变量的引用