Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 509
Steve Kuo Avatar asked Sep 10 '25 01:09

Steve Kuo


2 Answers

  1. Defensive programming (in case someone editing the code later adds a parameter or local with a conflicting name
  2. Make the code "self documenting," more obvious
like image 194
Doug Currie Avatar answered Sep 12 '25 15:09

Doug Currie


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.

like image 35
Daniel Spiewak Avatar answered Sep 12 '25 15:09

Daniel Spiewak