Shadowing instance variables with local variables in Java

前端 未结 2 1379
北恋
北恋 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:35

    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
    }
    

提交回复
热议问题