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

前端 未结 8 1791
北恋
北恋 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:21

    I occasionally use this because of autocompletion (makes life easier), but I clean them up afterwards.

    Remember, clarity is key. In this case, it's obvious that cont is a class variable, but if you were writing an enormous class with piles of instance variables, you might consider using this for clarity.

    You also only need to use this when there is a name collision, e.g.

    public class Ex {
        int num;
        public Ex(int num) {
            this.num = num; 
        }
    }
    

    In this example, whereas num = num would cause a collision, "this" avoids it. This is the only time it is absolutely necessary, but again, often clarity is a higher priority.

提交回复
热议问题