前几天,曾同学问我为什么 Java main 函数带有 static,我一时也不明白,只好说是 Java 的 main 函数的格式是规定的,我也一直这样写下来,然后赶紧去查。
原谅我,我忘记这是在哪个网站/论坛找到的了,因为当时没记录,只有在聊天记录中找到了当时copy下来的我觉得可以说得过去的解释。
The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:
public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}
Should the JVM call new JavaClass(int)? What should it pass for x?
If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn’t, because that will special-case your entire class – sometimes you have an instance that hasn’t been initialized, and you have to check for it in every method that could be called.
There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That’s why main is static.
个人对以上的理解就是为了避免无法确定该调用的构造函数而需将main函数设为先于类的构造而执行,故将其声明为 static
。