英文:
What happens when assign a return value from a method to a Class type variable in Java?
问题
我有一个公共类Dog。
方法1:
public Dog getDog(Dog dog){
if(dog.size > 0){
return dog;
}
return null;
}
方法2:
public Dog getNewDog(){
return new Dog();
}
最后,将方法返回值重新赋值:
Dog mydog = new Dog();
Dog d2 = new Dog();
Dog c = mydog.getDog(d2); // 我们是将一个引用变量赋回另一个引用吗?
Dog k = mydog.getNewDog(); // 我们是将一个新的Dog对象本身赋给Dog类型的变量。
现在,为什么我们总是将方法的返回值赋给引用变量?我在Java中到处都看到这个。
<details>
<summary>英文:</summary>
I have a public class Dog.
Method 1:
public Dog getDog(Dog dog){
if(dog.size>0){
return dog;
}
return null;
}
Method 2:
public Dog getNewDog(){
return new Dog();
}
Finally, assigning the method return value back:-
Dog mydog = new Dog();
Dog d2 = new Dog();
Dog c = mydog.getDog(d2); // are we assigning a reference variable back to another reference?
Dog k = mydog.getNewDog(); // Are we assigning a new dog object itself to the Dog type variable.
now, why do we always assign back value from a method to a Reference variable? I have seen this everywhere in Java.
</details>
# 答案1
**得分**: 1
让我试着回答你提出的注释中的问题:
A. 为什么我们总是将方法的返回值分配回一个引用变量?- 不一定正确。
有些类一旦给定了一个值,就无法更改它。这些被称为“不可变”。例如,`String` 是不可变的,所以一旦给它赋值,就无法更改该字符串。让我们看下面的例子:
String s1 = "1";
String s2 = s1.concat("2")
s2.concat("3");
System.out.println(s2); // 输出 12
输出是 **12**。原因是,每当调用更改值的方法时,您必须将其分配回去,否则您将丢失新值。对于一个不可变的对象,正如您所见,有必要重新分配。但是,这些是特殊的类。在 `Dog` 的情况下,您不必每次更改其属性时都进行分配。除非您明确需要创建一个新的 `Dog` 对象。
B. 我们是将一个新的狗对象本身分配给了狗类型的变量吗?
无论何时声明一个类型为引用的变量(它扩展自 Object 类),它都将被赋予 null。如果您尝试访问其属性,将会导致 `NullPointerException`。因此,请记住您必须为其分配一个值。
注意,`Dog k = mydog.getNewDog();` 在您的代码中等同于 `Dog k = new Dog();`。
C. 我们是将一个引用变量再次分配回另一个引用吗?
让我们看看您的代码:
public Dog getDog(Dog dog){
if(dog.size > 0){
return dog;
}
return null;
}
Dog d2 = new Dog();
Dog c = mydog.getDog(d2);
对于这段代码:
- 如果 `dog.size > 0` 为真,则 `d2` 和 `c` 将引用同一个对象。因此,您对其中一个进行的任何更改都将反映在两者上。
- 如果 `dog.size > 0` 为假,则 `c` 将被赋值为 `null`。
<details>
<summary>英文:</summary>
Let me try to answer the questions you have put as comments:
A. Why do we always assign back value from a method to a Reference variable? - Not necessarily true.
There are some classes once given a value, you can't change it. This are called `Immutable`. For instance, `String` is immutable, so once you assign it a value you can't change that same string. Let's see the following
example:
String s1 = "1";
String s2 = s1.concat("2")
s2.concat("3");
System.out.println(s2); // print out 12
The output is **12**. The reason is that, whenever you call a method that changes the value you have to assign it back or you will lose the new value.
For an `Immutable` object, as you can see, it is necessary that you reassign. But, this are special classes. In the case of `Dog`, you don't have to assign it every time change its properties. Unless you explicitly needed to create a new `Dog` Object.
B. Are we assigning a new dog object itself to the Dog type variable?
Whenever you declare a variable of type reference(that extends Object), it will be assigned null. And if you try to access its properties, it results in `NullPointerException`. So, keep in mind that you have to assign a value to it.
Note that `Dog k = mydog.getNewDog();` is equivalent to saying `Dog k = new Dog();` in your code.
C. Are we assigning a reference variable back to another reference?
Let's see your code:
public Dog getDog(Dog dog){
if(dog.size>0){
return dog;
}
return null;
}
Dog d2 = new Dog();
Dog c = mydog.getDog(d2);
For this piece of code:
- if `dog.size > 0` is true, `d2` and `c` will be referencing to the same object. So, any change you make to one of them will reflect on both.
- if `dog.size > 0` is false, `c` will be assigned `null`
</details>
# 答案2
**得分**: 0
所以你正在将新的 Dog 对象分配给变量 c 和 k,这将导致覆盖先前保存的狗。
虽然不一定非要这样做,但至少在三种情况下这样做可能很有用:
- 有时这种方式可以减少代码行数
- 如果你之前链接的对象在其他地方有使用,可能不希望到处都进行更改。如果一个方法返回一个新的(经过转换的)对象,你可以确保旧对象仍然可以在其他地方使用
- 这种模式可以用于构建器或链式调用。如果一个方法返回一只狗(无论是新的还是旧的),你可以直接在同一行上继续编写更多的方法调用。例如:mydog.getNewDog().bark();
<details>
<summary>英文:</summary>
So what you are doing is assignig new Dog objects to variable c and k, which results in overwriting the previously saved dogs.
It does not have to be done like this, but it can be useful in at least three cases:
- sometimes this way results in less lines of code
- if you used your previously linked object in other places, you might not want to change it everywhere. If a method returns a new (transformed) object, you can make sure the old object can still be used in other places
- this pattern could be used for builders or chaining. if a method returns a dog (no matter if it is a new or an old one) you may directly continue writing more method calls on the same line. Example: mydog.getNewDog().bark();
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论