10

I don't understand the real difference between this two codes, despite the fact that they both work.

If I use this class:

public class City {
    private String name;

I don't understand the difference between this method:

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

And this one:

public String getName(){
    return name;
}

The two methods work, but which one is the best to use, and why do they both work?

Thanks for the answers.

Joachim
  • 134
  • 1
  • 1
  • 8
  • 4
    The only time the two are different is when there is a parameter or local variable named `name`, in which case the `this` overides the rule that a reference binds to its closest definition. – Hot Licks May 07 '14 at 21:47
  • 1
    DupeChainOfDeath in action. This question shows up first on the SO search, but it is marked with a dupe of a dupe. Answers spread thin over several discussions. – Stepan May 20 '16 at 14:51

3 Answers3

16

The two methods are the same in most, but not all cases. Take the following constructor:

public City(String name){
    this.name = name;
}

There is a name field, and a name in local scope. Without this, the one in the local scope is implicitly used (right side of assignment) but with this we specifically refer to the field (left side of assignment). Before the assignment shown in the example I give, this.name would have the default value of null (assuming it was declared String name) while name would be the constructor parameter's value.

This is called shadowing and discussed formally in the JLS.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
9

"this" indicates the instance of the class.

In the following example, "this.a" is the a defined in the class (=10). While "a" (=20) is the local variable, defined in the constructor.

More details: http://en.wikipedia.org/wiki/Variable_shadowing

Example:

public class Test
{
    int a = 10;
    public Test()
    {
        int a = 20;
        System.out.println(a); // prints 20
        System.out.println(this.a); // prints the "a" defined in the class. In this case, 10
    }

    public static void main(String[] args)
    {
        new Test();
    }
}
Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64
1

In your example there is no difference. You're just choosing to be explict about the variable being a class variable. However if you did this:

public String getName(){
    String name = "David";
    return this.name;
}

It would mean a lot, because you're not returning the local variable named name, you're returning the class variable.

dckuehn
  • 2,427
  • 3
  • 27
  • 37