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.
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.
"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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With