Should I use “this” keyword when I want to refer t

2019-01-12 02:06发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

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


回答4:

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.



回答5:

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);
    }

}


回答6:

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
   }
}


回答7:

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.



回答8:

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().]