该对象在通过构造函数传递后不会更改。为什么?
The object does not change after being passed through a constructor. Why?
您好,我有以下代码:
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 总是按值传递所有内容。无论是原始类型还是对象。然而,在对象中,传递的是引用,这就是为什么您可以在通过方法传递对象后修改对象。我想测试当对象通过不同 class 的构造函数传递时是否同样适用。我发现对象没有改变。这对我来说似乎很奇怪,因为我只是在构造函数中传递对象的引用。它应该改变...?
I know Java always passes everything by value
这正是你的构造函数对传入的对象不做任何事情的原因。你可以改变传入对象的状态,但不能改变原始对象的引用多变的。
您好,我有以下代码:
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 总是按值传递所有内容。无论是原始类型还是对象。然而,在对象中,传递的是引用,这就是为什么您可以在通过方法传递对象后修改对象。我想测试当对象通过不同 class 的构造函数传递时是否同样适用。我发现对象没有改变。这对我来说似乎很奇怪,因为我只是在构造函数中传递对象的引用。它应该改变...?
I know Java always passes everything by value
这正是你的构造函数对传入的对象不做任何事情的原因。你可以改变传入对象的状态,但不能改变原始对象的引用多变的。