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

2019-01-27 11:57发布

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 parameters, but rather when it seems unnecessary.

Example:

public class Person {        
    private String name;

    public String toString() {
        return this.name;
    }
}

In toString, why not just reference name as name?

return name;

What does this.name buy?

Here's a stackoverflow question whose code has this pre-pending.

16条回答
老娘就宠你
2楼-- · 2019-01-27 12:58

Same reason why some people like to prepend private data members with "m_" or name interfaces "IFoo". They believe it increases readability and clarity. Whether or not you agree with conventions like these is a matter of taste.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-27 13:00

"this" prevents confusion with instance variables with the same name in the parent class/es.

It's pretty much the complement to prepending with "super".

查看更多
劫难
4楼-- · 2019-01-27 13:01

The code is simplier reading. Another good practice, in my opinion, is calling the getXXX() in toString() too (instead then this.XXX), beacuse the getXXX() can have an important logic.

I think that use the name of attribute without this is'nt a good idea for the maintenance of the application.

查看更多
我想做一个坏孩纸
5楼-- · 2019-01-27 13:02

Apart from the disambiguation with method parameters, it buys you nothing. Maybe clarity/readability but that really depends on your style.

查看更多
登录 后发表回答