1

i noticed that when i used the keyword 'this' on a static method it compiled just fine. For example:

class Foo {
public void A(){}

public static void B() {}

public void C() {
  this.A(); //compiles
  Foo.B();  //compiles
  this.B(); //compiles, but should it?
}
blue_ego
  • 1
  • 1
  • 4
  • 12
  • 2
    yes............ – luk2302 Oct 23 '17 at 19:42
  • you are mixing things up. Yes you can call a static class method from an instance, although you normally don't. you can't call an instance method from a static method though. You can't use `this` in a static method. – Jack Flamp Oct 23 '17 at 19:45
  • It's a bit odd, yes, but it's possible. The reason is (I believe) so that you can invoke `B()` from the instance method `C`, without over-complicating the name resolution rules with more exceptions. In other words, the same rule that would let you invoke `B()` also lets you invoke `this.B()` or `fooInstance.B()`. If they wanted to allow `B()` but disallow the other forms, they would have to add more rules to the language. Related: https://stackoverflow.com/questions/2223663/what-happens-when-a-static-method-is-invoked-using-a-null-object-reference – yshavit Oct 23 '17 at 19:46
  • I was typing up my answer when your question got the dupe hammer. You can read it here https://stackoverflow.com/a/46897897/2033671 –  Oct 23 '17 at 20:25

1 Answers1

0

this keyword is available to only class run time instances or class objects.

Class Objects can access both static and non static methods so not a problem.

Max08
  • 955
  • 1
  • 7
  • 16