4
class SomeClass {
   public void someMethod(){}

   public void otherMethod(){
      //Calling someMethod()
   }
}

Whats the difference when you call an instance method as:

 --> someMethod(); OR this.someMethod();

vs

--> SomeClass.this.someMethod();

amit.shipra
  • 167
  • 2
  • 16
  • 1
    You can't call a method like `SomeClass.this.someMethod();` – Amit Bera Jul 24 '18 at 17:47
  • 6
    There are contexts where `SomeClass.this.someMethod()` is a valid method call (for instance, non-static nested classes). – VeeArr Jul 24 '18 at 17:48
  • Possible duplicate of [java "this" keyword proper use](https://stackoverflow.com/questions/28805295/java-this-keyword-proper-use) – VeeArr Jul 24 '18 at 17:51
  • 2
    See also: https://stackoverflow.com/questions/24947750/java-this-keyword-preceded-by-class-name – VeeArr Jul 24 '18 at 17:51
  • @VeeArr could you give us an example (maybe some code) where `SomeClass.this.someMethod()` would be a valid method call? – lealceldeiro Jul 24 '18 at 18:15
  • 2
    `class A{ void someMethod(){} class B{ B(){A.this.someMethod();} void someMethod(){} } }` the `someMethod` in `B` hides the one in `A`, so you have to use `A.this` to call it. – NickL Jul 24 '18 at 18:28
  • Thanks @NickL :) I just realized about this while reading https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html (_Accessing Local Variables of the Enclosing Scope_ topic) – lealceldeiro Jul 24 '18 at 19:49
  • @NickL I just thought the last syntax is not a common scenario, so I posted a community wiki in order to let future reader find it easily. – lealceldeiro Jul 24 '18 at 19:59

1 Answers1

3

There is no difference from doing:

//...
public void otherMethod(){
  someMethod();
}
//...

to doing

//...
public void otherMethod(){
  this.someMethod(); // `this` in this case refers to the class instance 
}
//...

Now if you would have

class SomeClass {
   public static void someMethod(){}

   public void otherMethod(){
      //Calling someMethod()
   }
}

you could do:

//...
public void otherMethod(){
  SomeClass.someMethod(); // as the method is static you don't need to call it from an instance using `this` or omitting the class 
}
//...

And lastly this syntax SomeClass.this.someMethod(); would not be correct in all scenarios. An example of where this could be used (correct) is as follow:

class SomeClass {
   public void someMethod(){}

   public void otherMethod(){
      //Calling someMethod()
   }

    class OtherClass {

        public OtherClass() {
            // OtherClass#someMethod hides SomeClass#someMethod so in order to call it it must be done like this
            SomeClass.this.someMethod();
        }

        public void someMethod(){}
    }
}
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80