30

My teacher says that when I try to access an instance variable within a method I should always use the this keyword, otherwise I would perform a double search. A local scope search and then an instance scope search.

Example:

public class Test(){
    int cont=0;
    public void Method(){
        System.out.println(cont);//Should I use This.cont instead?
    }
}

I hope he is wrong, but I can't find any argument.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Juan Herrera
  • 810
  • 1
  • 10
  • 16
  • 12
    *"Double search*"??? Does your teacher realize that name lookup is done at compile time? – Pubby Apr 05 '13 at 03:51
  • Use of "this" is an extension of Hungarian notation, in my view. In other words, it shouldn't be defaulted to in this day and age, when sensible Java developers code via an IDE. – ayahuasca May 24 '17 at 06:40

8 Answers8

40

No, only use this when you have a name conflict such as when a method parameter has the same name as an instance field that it is setting.

It can be used at other times, but many of us feel that it simply adds unnecessary verbiage to the code.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 14
    This kind of code has poor readability. Always use `this`. Otherwise everytime a reader sees a reference to a variable they wonder whether it's a local or an instance variable. – MohamedEzz Jan 19 '17 at 13:03
  • 8
    @MohamedEzz: we'll agree to disagree, but I do respect your opinion, and am perfectly fine with your down-vote since it was done for what you believe is a valid reason and for your commenting on it. Sincerely, thank you for commenting. – Hovercraft Full Of Eels Jan 19 '17 at 17:19
  • 3
    I'm with Hovercraft - first of all, if you write code that is tidy, well structured and cohesive, it should be clear to any competent programmer that a variable is a member. Secondly, IDEs make identifying member variables trivial because of colour coding. – ayahuasca May 24 '17 at 06:33
  • Elegant code doesn't mean that it's readable. `this` would save a lot of brainpower. – Gayan Weerakutti Dec 09 '19 at 09:39
25

You must use this if required because of a name conflict, though it's better to avoid those entirely.

You may use this if you desire. It is purely a matter of taste.

You should use this in your schoolwork if your teacher demands it.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • 3
    +1 for hinting at the larger point: every environment you work in is going to have coding conventions, and you should follow them even if you don't like them, because consistent code is easier on the eyes. If the teacher's convention is to always use `this`, so be it. (But there's no double search going on.) – yshavit Apr 05 '13 at 04:51
  • @yshavit I think it is not about the convention here. It is about the (wrong) reason the teacher is giving. If it had anything to do with the convention of the teacher, they would have mentioned that, or wouldn't have said anything. The teacher is simply mistaken. They might thank the student for correcting them. – Solace Feb 15 '16 at 12:26
2

this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance.
See Java - when to use 'this' keyword
Also This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.

public class Test
{
int a;

public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}

So you may say that
this keyword can be used for (It cannot be used with static methods):

        1)To get reference of an object through which that method is 
        called within it(instance method).
        2)To avoid field shadowed by a method or constructor parameter.
        3)To invoke constructor of same class.
        4)In case of method overridden, this is used to invoke method of current class.
        5)To make reference to an inner class. e.g ClassName.this
Community
  • 1
  • 1
Freak
  • 6,786
  • 5
  • 36
  • 54
  • Can you make an example on 4)In case of method overridden, this is used to invoke method of current class. Tried to test it, but can't detect situation where it's valid. – brnfd Feb 14 '14 at 20:44
  • share your code as question , probably you will get the answer – Freak Feb 14 '14 at 23:27
2

Your teacher is correct that it will result in double search for compiler if you don't make use of this keyword. First the compiler will search at local scope and then the instance scope if the compiler is unable to find the variable at local scope.

Also, while the compiler is converting your code to bytecode, the compiler will prefix all the instance variables with this keyword. So, if you yourself make use of this keyword, you are actually reducing the burden to the compiler and the code will be compiled faster.

Prasad
  • 5,946
  • 3
  • 30
  • 36
  • 9
    I wouldn't feel sorry for the compiler. I mean, I also make it strip out my comments! – Andrew Lazarus Apr 05 '13 at 05:25
  • 1
    I agree with you. It is just a personal taste. Another thing is that if the code goes long, then it will also increase understandibility of the code for the new person to understand that you are using an instance variable and not a local variable. – Prasad Apr 05 '13 at 05:32
1

Since everybody has given examples of disambiguating names, I will give an example when using this help:

public class Person {
    private final firstName;
    private final lastName;
    private final Date birthdate;
    private final Address address;

    @Override
    public boolean equals(Object otherObject) {
        if (!(otherObject instanceof Person) {
            return false;
        }

        Person otherPerson = (Person) otherObject;

        // Using this here help distinguishing the current instance and the other.
        return this.firstName.equals(otherPerson.firstName)
            && this.lastName.equals(otherPerson.lastName)
            && this.birthdate.equals(otherPerson.birthDate)
            && this.address.equals(otherPerson.address);
    }

}
Genzer
  • 2,921
  • 2
  • 25
  • 38
0

this only applies to the case where a parameter has the same name as a class property.

public class Dog {
   String name;
   public Dog(String name) {
      name = name; //but which name? Are we just assigning a variable to itself?
      // here you could say this.name = name. Or you could rename one of the variables to resolve ambiguity
   }
}
0

I occasionally use this because of autocompletion (makes life easier), but I clean them up afterwards.

Remember, clarity is key. In this case, it's obvious that cont is a class variable, but if you were writing an enormous class with piles of instance variables, you might consider using this for clarity.

You also only need to use this when there is a name collision, e.g.

public class Ex {
    int num;
    public Ex(int num) {
        this.num = num; 
    }
}

In this example, whereas num = num would cause a collision, "this" avoids it. This is the only time it is absolutely necessary, but again, often clarity is a higher priority.

  • 1
    I'm not sure which IDE you use, but I do know that with Eclipse, there's no need to use `this` when autocompleting since ctrl-space will bring up autocompletion without `this`. – Hovercraft Full Of Eels Apr 05 '13 at 03:53
  • @HovercraftFullOfEels Hmm, I've never actually looked into that. I'm using NetBeans; not sure what the shortcut is there. I'll have to look into that! –  Apr 05 '13 at 03:55
0

Another place that this is often used for readability is when an inner class object is referring to a field of its containing object.

public class Foo {

    String foostring;
    /* snip lots of code */
    private class Foohelper {
        void helperMethod(String bazstring) {
             Foo.this.foostring = bazstring;
             // etc.
        }
    }
}

The compiler doesn't need this, but it makes the situation where to look for foostring more clear. Other than this (!), I only fully qualify field names in the constructor where they may be hidden by parameter names, as many other posters have illustrated here.

[Edit: Now that I think about it, there are places the compiler needs this, e.g., if Foohelper.toString() wants to call Foo.toString().]

Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53