0
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?

Emma
  • 27,428
  • 11
  • 44
  • 69
Amit
  • 53
  • 13
  • `new GFG()` does create an instance. So what are you actually asking? – Seelenvirtuose May 29 '19 at 18:21
  • Four letters - `this` – Boris the Spider May 29 '19 at 18:22
  • 1
    There has to be a dupetarget for this. – T.J. Crowder May 29 '19 at 18:23
  • Possible duplicate of [*When should I use “this” in a class?*](https://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class) – T.J. Crowder May 29 '19 at 18:24
  • In order for pri() to be called you must of had an instance (created with the "new" keyword in your main). Once pri() is executing, you **ARE IN THAT INSTANCE**...and calling mod() runs it in the same instance that you are in. Thus the "this" keyword, which means find the thing inside the currently running instance. – Idle_Mind May 29 '19 at 18:33

2 Answers2

0

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0
class GFG {
    public static void main (String[] args) {
        GFG g=new GFG();
        g.pri();
    }
}

It works, because you call non-static pri() method of instance of GFC.

class GFG {
    public static void main (String[] args) {
        pri();
    }
}

will fails, because you call non-static pri() from static main()

Bor Laze
  • 2,458
  • 12
  • 20