本地变量和实例变量的名称相同。

huangapple go评论73阅读模式
英文:

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;

huangapple
  • 本文由 发表于 2020年8月26日 06:07:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63587764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定