英文:
Local variable and instance variable has the same name
问题
我不太明白这个情况中发生了什么过程:
class SomeClass {
int val = 50;
String str = "default";
public SomeClass(int val) {
val = val;
}
}
这个语句中的 val = val 到底发生了什么?
英文:
I dont understand exactly the process that happened in this case:
class SomeClass {
int val = 50;
String str = "default";
public SomeClass(int val) {
val = val;
}
}
what exactly happen in this statement val = val ?
答案1
得分: 1
代码如图所示是错误的。这里的意图是将局部变量 val
的值赋给实例变量 val
。然而,没有限定词,这段代码只是将局部变量重新分配给自身。如果在构造函数参数中添加一个 final
,您将看到这一点。
您想要的是 this.val = val
。通常习惯将两者命名相同以增加可读性,但要用 this
限定实例变量。
您还想要一本基础的Java书。
英文:
The code, as shown, is wrong. The intent here is to assign the value of local variable val
to the instance variable val
. However, without a qualifier, this code just reassigns the local variable to itself. You’ll see it if you add a final
to the constructor parameter.
What you want is this.val = val
. It’s common practice to name both the same for legibility, but qualify the instance variable with this
.
You also want a basic Java book.
答案2
得分: 1
这将把本地变量 val
的值赋值给它本身。要将本地的 val
赋值给实例的 val
,请使用 this
关键字:
this.val = val;
英文:
> what exactly happen in this statement val = val ?
This assigns the value of the local variable val
to itself. To assign the local val
to the instance val
, use the this
keyword:
this.val = val;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论