Should I use “this” keyword when I want to refer to instance variables within a method?

前端 未结 8 1805
北恋
北恋 2020-12-03 16:53

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.

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 17:46

    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
    

提交回复
热议问题