Java主方法的方法签名是:

public static void main(String[] args) {
    ...
}

为什么这个方法必须是静态的?


当前回答

The static key word in the main method is used because there isn't any instantiation that take place in the main method. But object is constructed rather than invocation as a result we use the static key word in the main method. In jvm context memory is created when class loads into it.And all static members are present in that memory. if we make the main static now it will be in memory and can be accessible to jvm (class.main(..)) so we can call the main method with out need of even need for heap been created.

其他回答

我不知道JVM是否在对象实例化之前调用main方法…但是main()方法是静态的还有一个更有力的原因…当JVM调用类的主方法(比如Person)时。它通过"Person.main()"调用它。您可以看到,JVM通过类名调用它。这就是为什么main()方法应该是静态和公共的,以便JVM可以访问它。

希望有帮助。如果是的话,请在评论中告诉我。

主方法总是需要是静态的,因为在运行时JVM不会创建任何对象来调用主方法,正如我们所知,在java中静态方法是唯一可以使用类名调用的方法,所以主方法总是需要是静态的。

更多信息请访问这个视频:https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be

这只是一种惯例。JVM当然可以处理非静态的主方法,如果这是惯例的话。毕竟,您可以在类上定义静态初始化器,并在到达main()方法之前实例化无数对象。

c++、c#和Java中的主要方法是静态的。

这是因为它们可以被运行时引擎调用,而无需实例化任何对象,然后main主体中的代码将完成其余的工作。

public静态void关键字意味着Java虚拟机(JVM)解释器可以调用程序的主方法来启动程序(public),而无需创建类的实例(static),并且程序结束时不会将数据返回给Java VM解释器(void)。

来源: 要领,第1部分,第2课:构建应用程序