Search code examples
javaconstructorstaticinstance

Why can a Java static method call a constructor, but not refer to this?


My Assumptions:

  1. Static method cannot cannot call non-static methods.
  2. Constructors are kind of a method with no return type.

Given this example...

    public class Main {
        public static void main(String[] args) {
            Main p = new Main();  // constructor call
            k();  // [implicit] `this` reference
        }

        protected Main() {
            System.out.print("1234");
        }

        protected void k() {
        }
    }
  • this line prints 1234: Main p = new Main()
  • this line throws an Exception: k()

Why did the example code do those two things? Don't they conflict with my above Assumptions? Are my Assumptions correct?


Solution

  • 1 - Static method cannot cannot call non-static methods.

    Sure they can, but they need an object to call the method on.

    In a static method, there's no this reference available, so foo() (which is equivalent to this.foo()) is illegal.

    2 - Constructors are kind of a method with no return type.

    If they should be compared to methods, I would say constructors are closer to non-static methods (since there is indeed a this reference inside a constructor).

    Given this view, it should be clear to you why a static method can call a constructor without any problems.


    So, to sum it up:

    Main p = new Main();
    

    is okay, since new Main() does not rely on any existing object.

    k();
    

    is not okay since it is equivalent to this.k() and this is not available in your (static) main method.