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

8
  • 1
    You can't call a method like SomeClass.this.someMethod(); Commented Jul 24, 2018 at 17:47
  • 6
    There are contexts where SomeClass.this.someMethod() is a valid method call (for instance, non-static nested classes). Commented Jul 24, 2018 at 17:48
  • Possible duplicate of java "this" keyword proper use Commented Jul 24, 2018 at 17:51
  • 2
    See also: stackoverflow.com/questions/24947750/… Commented Jul 24, 2018 at 17:51
  • 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. Commented Jul 24, 2018 at 18:28

1 Answer 1

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(){}
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.