Java - when “this” is the only way to go?

后端 未结 5 1074
眼角桃花
眼角桃花 2021-01-28 13:21

The following code runs for both var = putVar; & this.var = putVar;

I understand: \"this\" is used to identify that - \"put this value for just \'my\'

5条回答
  •  借酒劲吻你
    2021-01-28 13:25

    If a class has an instance variable with some name (say myVar), and a method has a LOCAL variable with the exact same name (myVar), then any reference to the variable will refer to the LOCAL variable. In cases such as these, if we want to specify the class's instance variable, we need to say this.myVar. As stated before, this is particularly useful when we want to have setters in which the parameter name is the same as the instance variable that it sets:

    public void setMyVar(int myVar) {
        this.myVar = myVar; // If we said myVar = myVar;, we'd just set the local
                            // variable to itself, which would NOT be what we want.
    }
    

提交回复
热议问题