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:36

The only place I use this is in constructors in classes where some/most of the fields of the class can be supplied by the constructor. I use this rather than using short names for the method signature, it just seems more consistent than abbreviating.

For example in a class "Rational"

Rather than doing

class Rational
{
    int denominator;
    int numerator;

    public Rational(int d, int n)
    {
        denominator = d;
        numerator = n;
    }
}

I do this.

class Rational
{
    int denominator;
    int numerator;

    public Rational(int denominator, int numerator)
    {
        this.denominator = denominator;
        this.numerator = numerator;
    }
}

That way callers know more about what the constructors parameters are for.

查看更多
虎瘦雄心在
3楼-- · 2019-01-27 12:39

I most often see people do this because it triggers the intellisense. I personally prefer to leave off the "this." because it creates more code without any value.

查看更多
\"骚年 ilove
4楼-- · 2019-01-27 12:39

I think there's nothing wrong if you put in this before the property name. This helps disambiguate the property from local variables should you have any declared with the same name (which may happen in a constructor when you initialize properties).

It doesn't affect performance, it doesn't create any problems for readability (if at all it makes reading easier).

So I don't think we need to worry about this. Let the programmers make their own choice.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-27 12:40

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.

查看更多
何必那么认真
6楼-- · 2019-01-27 12:43

I try to use 'this.whatever' when writing large chunks of code, because it was easier to figure out what was being referenced. When reading large chunks of code written by other people, at certain points I would often get confused as to whether they were referencing instance variables or local variables.

查看更多
Bombasti
7楼-- · 2019-01-27 12:46

They are perhaps a Python programmer and get tortured/lost/confused without an explicit this.

查看更多
登录 后发表回答