- 一个暂且说的过去的解释
The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:
1 public class JavaClass{ 2 protected JavaClass(int x){} 3 public void main(String[] args){ 4 } 5 }
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。
参考:http://liunian.info/why-java-main-static.html
2.
static关键字,告知编译器main函数是一个静态函数。也就是说main函数中的代码是存储在静态存储区的,即当定义了类以后这段代码就已经存在了。如果main()方法没有使用static修饰符,那么编译不会出错,但是如果你试图执行该程序将会报错,提示main()方法不存在。因为包含main()的类并没有实例化(即没有这个类的对象),所以其main()方法也不会存。而使用static修饰符则表示该方法是静态的,不需要实例化即可使用。