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

后端 未结 3 602
梦谈多话
梦谈多话 2021-02-08 02:58

My Assumptions:

  1. Static method cannot cannot call non-static methods.
  2. Constructors are kind of a method with no return type.
3条回答
  •  误落风尘
    2021-02-08 03:16

    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.

提交回复
热议问题