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

2019-01-12 01:40发布

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.

8条回答
一夜七次
2楼-- · 2019-01-12 02:21

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.

查看更多
Rolldiameter
3楼-- · 2019-01-12 02:25

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

}
查看更多
迷人小祖宗
4楼-- · 2019-01-12 02:28

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.

查看更多
SAY GOODBYE
5楼-- · 2019-01-12 02:30

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
   }
}
查看更多
太酷不给撩
6楼-- · 2019-01-12 02:31

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
查看更多
Evening l夕情丶
7楼-- · 2019-01-12 02:39

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

查看更多
登录 后发表回答