Is any different between this two types?
public class MyClass{
String name;
public MyClass(String nn){
this.name = nn;
name = nn;
}
}
Is any different between this two types?
public class MyClass{
String name;
public MyClass(String nn){
this.name = nn;
name = nn;
}
}
No, they are exactly equivalent. Sometimes it is useful to be explicit by using the this
keyword because there might be two variable with the same name but different scope, like this:
public class MyClass {
String name;
public MyClass(String name) {
name = name; // Obviously doesn't work
this.name = name; // Now it works.
}
}
But since you are not in this situation, it doesn't make a difference.
No there is no difference in your case.
But helps in situations like these:
public MyClass(String name){
this.name = name; //works
name = name; // doesn't
}
In your particular case the unqualified name resolves to this.name
, but in other situations this may not be so. The obvious case is when the constructor parameter has the same name, but there are other, more complex situations involving inner classes where actually putting in this
spoils the name resolution.
So, if you are only interested in your narrow and specific case, the answer is clear-cut, but in general you must be wary of the subtleties of Java's variable name resolution.
There is no difference.
You might need to use this
if name of the parameter is equal to the field name.
public MyClass(String name){
this.name = name;
}
there is no such difference but 'this' must be used
public MyClass(String name){
this.name = name; // it works
name = name; // it doesn't
}
You need to know why we use 'this' keyword. so here is your answer