Should I use “this” keyword when I want to refer to instance variables within a method?

前端 未结 8 1801
北恋
北恋 2020-12-03 16:53

My teacher says that when I try to access an instance variable within a method I should always use the this keyword, otherwise I would perform a double search.

8条回答
  •  情话喂你
    2020-12-03 17:22

    this only applies to the case where a parameter has the same name as a class property.

    public class Dog {
       String name;
       public Dog(String name) {
          name = name; //but which name? Are we just assigning a variable to itself?
          // here you could say this.name = name. Or you could rename one of the variables to resolve ambiguity
       }
    }
    

提交回复
热议问题