-2

Why is it possible to use a non-static method inside the class it's been created without an object but impossible to do inside the Main method if it's also inside the class for example :

public class C {
    public void f() {...};
    
    public void g() { f() }; //no error
    
    public static void Main(String[] args) {
        f(); //compilation error.
    }
}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
Pompa
  • 11
  • 3
  • inside g `f()` is the short for `this.f()` – Turo Jun 09 '21 at 19:30
  • In order for you to syntactically/legally call `f()` or `g()` there has already been a constructor called somewhere before then (i.e. you can only call `instanceOfC.f()`, or `instanceOfC.g()`. A static method can be called without first constructing an instance of the class, so calls no non-static methods would cause a problem. And, as Turo mentioned, it's assumed that when you call an instance method from a within a class, you're calling it on the current instance (i.e. `this`) – Gus Jun 09 '21 at 19:36

1 Answers1

1

Inside an instance of a class, there is an implicit this when invoking methods in it.

public class C {

    public void f() { }
    public void g() {
        this.f(); // not a compile-time error; this refers to an instance of C
    }
}

Inside a static method, there is no this because static methods have no instance attached to them, thus it would be a compile-time error to try to refer to it.

From the JLS:

A class method is always invoked without reference to a particular object. It is a compile-time error to attempt to reference the current object using the keyword this (§15.8.3) or the keyword super (§15.11.2).

So in the static method, you need an instance of C to invoke f.

public static void main(String[] args) {
    new C().f();
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • In short: heed the words of "As Time Goes By", famously heard in the film Casablanca: you must remember **this**, – iggy Jun 10 '21 at 01:11