-1

Is any different between this two types?

public class MyClass{
String name;

public MyClass(String nn){
this.name = nn;
name = nn;
}
}
Sajad
  • 2,273
  • 11
  • 49
  • 92
  • which codes? if you asking about difference between `this.name = nn` and `name = nn` then for this case there isno difference – user902383 Aug 16 '13 at 11:27

5 Answers5

5

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.

devrobf
  • 6,973
  • 2
  • 32
  • 46
  • Nice, Please see my previous question: http://stackoverflow.com/questions/18177249/initialize-variable-with-constructor – Sajad Aug 16 '13 at 11:32
5

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
}
rocketboy
  • 9,573
  • 2
  • 34
  • 36
2

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Nice, Please see my previous question: http://stackoverflow.com/questions/18177249/initialize-variable-with-constructor – Sajad Aug 16 '13 at 11:31
1

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;
}
Tala
  • 8,888
  • 5
  • 34
  • 38
  • Nice, Please see my previous question: http://stackoverflow.com/questions/18177249/initialize-variable-with-constructor – Sajad Aug 16 '13 at 11:31
0

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

Surinder ツ
  • 1,778
  • 3
  • 16
  • 27