Why can other methods be “static” but a constructor cannot?

后端 未结 15 1211
借酒劲吻你
借酒劲吻你 2020-12-04 17:59

I do not understand why the main method has to be static. I understand static variables but static methods are difficult for me to grasp. Do static method exists so that one

15条回答
  •  借酒劲吻你
    2020-12-04 18:23

    On page 272 of Thinking In Java, 4th Edition, by Bruce Eckel, it says:

    ²The constructor is also a static method even though the static keyword is not explicit. So to be precise, a class is first loaded when any of its static members is accessed.

    A little bit more context.

    ... the compiled code for each class exists in its own separate file. That file isn't loaded until the code is needed. In general you can say "class code is loaded at the point of first use." This is usually when the first object of that class is constructed, but loading also occurs when a static field or static method is accessed.²

    This makes a lot of sense, if you think about the rule that says that a static method can't use non-static methods of the same class. I had this doubt a couple weeks ago when I couldn't understand how, using the Singleton Pattern, you could access the constructor inside the static method that is used to create a new instance of that class. Today I was flipping through the book and I came across this explanation.

    It also makes sense in a way that, if the constructor wasn't static, you'd first need an instance of that class to be able to access it, but I guess this could spark up the old discussion about the chicken or the egg.

    Hope it helped!

提交回复
热议问题