Shadowing instance variables with local variables in Java

前端 未结 2 1402
北恋
北恋 2021-01-27 13:54

I have read that \" a variable is shadowed if there is another variable with the same name that is closer in scope\". I found this Point class with a constructor as an example:<

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-27 14:37

    I thought that "x = x" in the constructor would be like "23 = 23".

    Within the constructor, the meaning of the simple name x is always just the parameter. So the assignment x = x in the constructor takes the value of the x parameter and assigning it to the x parameter as well. The instance variable is never touched. (It's not clear what you mean by 23 = 23;, so I can't tell whether or not that's accurate.) Basically, this is a no-op and some IDEs will give you a warning about it.

    To force it to copy to the instance variable, you want:

    this.x = x;
    

    (And likewise for y, of course.)

提交回复
热议问题