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

后端 未结 3 620
梦谈多话
梦谈多话 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:09

    No. Constructors aren't ordinary methods in this respect. The whole point of the constructor is to, well, construct a new instance of the class.

    So it can be invoked in static scope too. Just think about it: if you needed an existing instance of your class in order to create a new instance of it, you would simply never be able to instantiate it ever.

    A few clarifications:

    Static method cannot cannot call non-static methods.

    Not quite. You can call a nonstatic method from inside a static method, just you need to scope it to a specific object of that class. I.e.

    p.k();
    

    would work perfectly in your code sample above.

    The call

    k();
    

    would be fine inside an instance (nonstatic) method. And it would be equivalent to

    this.k();
    

    The implied this refers to the current instance of the class. Whenever the compiler sees an unqualified call like k() within an instance method, it will automatically scope it with this. . However, since static methods aren't tied to any instance of the class, you (and the compiler) can't refer to this inside a static method. Hence you need to explicitly name an instance of the class to call an instance method on.

提交回复
热议问题