Shadowing instance variables with local variables in Java

断了今生、忘了曾经 提交于 2019-12-02 22:24:18

问题


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:

public class Point {
    public int x = 0;
    public int y = 0;

    public Point(int x, int y) {
        x = x;
        y = y;
    }
}

Then I created an object of the Point class in the CreateObjectDemo class below and printed the value of the variable x.

public class CreateObjectDemo {
    public static void main(String[] args) {

    Point originOne = new Point(23, 94);

    System.out.println(originOne.x);

    }

}

After running the compiler, it prints 0. But why doesn't it print 23? I thought that "x = x" in the constructor would be like "23 = 23". Did I misunderstand the definition of shadowing variables?


回答1:


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.)




回答2:


0 is the default value for int type variables, and as the warning says, you're shadowing the variables in the constructor so the object variable is never assigned to.

public Point(int x, int y) {
    x = x; //assign value of local x to local x
    y = y; //assign value of local y to local y
}

You need to use this keyword to refer to the object variables x and y instead of the local variables:

public Point(int x, int y) {
    this.x = x; //assign value of local x to object variable x
    this.y = y; //assign value of local y to object variable y
}


来源:https://stackoverflow.com/questions/23432722/shadowing-instance-variables-with-local-variables-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!