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

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

    Rules are simple:
    1 - Static method cannot cannot call non-static methods.

    That's simply not true. A static method can call a non-static method, just via a "target" reference. For example, this is fine in a static method:

    Integer x = Integer.valueOf(10);
    int y = x.intValue(); // Instance method!
    

    The real point is "there's no this reference within a static method".

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

    That's not a really useful model, to be honest. It makes more sense (from the caller's point of view) to consider a constructor as a static method with a return type that's the same as the declaring class, but even that's not a perfect model by any means.

    I suggest you think of a constructor as a different type of member. Embrace the differences between constructors and methods, instead of trying to hide them.

提交回复
热议问题