Java主方法的方法签名是:

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

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


当前回答

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

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

其他回答

让我用更简单的方式来解释这些事情:

public static void main(String args[])

除了applet,所有Java应用程序都从main()开始执行。

关键字public是一个访问修饰符,允许从类外部调用成员。

使用Static是因为它允许调用main()而不必实例化该类的特定实例。

Void表示main()不返回任何值。

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.

这只是一种惯例,但可能比另一种更方便。使用静态主程序,调用Java程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。

如果主方法不是静态的,则需要从程序外部创建主类的对象。你想怎么做呢?

来自java.sun.com(网站上有更多信息):

主要方法是静态的,以使Java VM解释器能够在不首先创建控件类实例的情况下启动类。控件类的实例在程序启动后在main方法中创建。

我的理解一直很简单,就像任何静态方法一样,可以在不创建相关类的实例的情况下调用主方法,允许它在程序中的任何其他方法之前运行。如果它不是静态的,你就必须在调用它之前实例化一个对象——这就产生了一个“先有鸡还是先有蛋”的问题,因为main方法通常是你在程序开始时用来实例化对象的。