Search code examples
javamethodsstaticclass-methodnon-static

Calling non static method without class instance inside a non static method


class GFG {
public static void main (String[] args) {
    GFG g=new GFG();
    g.pri();

}

void pri(){    
  mod();
}
void mod()
{
    System.out.println("HHI");
}

}

In this following code when i am calling a mod() method inside a non static method without creating class instance for mod() method it does work and given Output "Hi"; According to the definition of non static method cannot be called without Class instance;

How it does work?


Solution

  • It has an instance, the one you created in main, which you used when doing g.pri(). Within an instance method like pri, the instance it was called on is available as this, and this. is optional. In an instance method, these two statements do exactly the same thing:

    mod();
    this.mod();
    

    If you don't include the this., the Java compiler adds it for you.

    (As a matter of opinion, I suggest you include it, at the very least for fields, since otherwise in the code x = y + 1 you have no idea whether x and y are locals in the method or fields on the instance.)