Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between this.variable and variable in Java [duplicate]

Tags:

java

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.

like image 359
Joachim Avatar asked May 07 '14 21:05

Joachim


2 Answers

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.

like image 72
nanofarad Avatar answered Sep 22 '22 22:09

nanofarad


"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();
    }
}
like image 25
Alexandre Santos Avatar answered Sep 19 '22 22:09

Alexandre Santos