Please explain “this” to me

前端 未结 6 1333
轮回少年
轮回少年 2021-01-01 05:03

I\'ve read hundreds of explanations on \"this\" in java and I\'m really having trouble grasping it. I\'m learning android and java side-by-side, I know it\'s harder that wa

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 05:11

    Instance methods (those not declared static) of a class can only be executed by reference to some instance of the class. For example:

    class Foo {
        public void doSomething() {
            // "this" refers to the current object
            . . .
        }
        . . .
    }
    
    // then later:
    Foo aFoo = new Foo();
    aFoo.doSomething(); // "this" will be equal to "aFoo" for this call
    
    // The following is illegal:
    doSomething();
    
    // so is this:
    Foo.doSomething();
    

    Inside the method doSomething(), the variable this refers to the specific instance of Foo that was used to invoke the method (in this example, the current object referenced by aFoo).

提交回复
热议问题