In Java, why do people prepend fields with `this`?

前端 未结 16 2148
广开言路
广开言路 2020-12-20 11:18

When referencing class variables, why do people prepend it with this? I\'m not talking about the case when this is used to disambiguate from method

16条回答
  •  执笔经年
    2020-12-20 11:47

    Sometimes it is necessary to disambiguate:

    public void setFoo(Bar foo) {
        this.foo = foo;
    }
    

    At other times, it's just a stylistic thing. On the whole, I try to avoid this.blah wherever possible as it is more verbose. In case you're wondering, the resultant bytecode is exactly the same.

提交回复
热议问题