Java主方法的方法签名是:

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

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


当前回答

The main method of the program has the reserved word static which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating computer memory to store the program and its data, etc.. A dynamic context is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.

其他回答

这背后的原因很简单,因为对象不需要调用静态方法,如果它是非静态方法,java虚拟机先创建对象,然后调用main()方法,这将导致额外的内存分配问题。

Static表示该方法是类方法。并且调用时不需要任何类的对象。

public关键字是一个访问修饰符,它允许程序员进行控制 类成员的可见性。当类成员前面有public时,则 成员可以由声明它的类之外的代码访问。

public的反义词是private,它防止成员被定义在类外部的代码使用。

在这种情况下,main()必须声明为public,因为必须调用它 当程序启动时,由其类之外的代码执行。

关键字static允许 Main()被调用,而不必实例化类的特定实例。这是必要的,因为Java解释器在创建任何对象之前调用main()。

关键字void只是告诉编译器main()不返回值。

使用Java命令运行Java虚拟机(JVM)时,

java ClassName argument1 argument2 ...

当您执行您的应用程序时,您指定它的类名作为java命令的参数,如上所述

JVM尝试调用您指定的类的主方法

-在这一点上,类的对象还没有被创建。 将main声明为静态允许JVM在不创建的情况下调用main 类的实例。

让我们回到命令

ClassName是JVM的命令行参数,它告诉JVM要执行哪个类。在ClassName之后,您还可以指定一个字符串列表(由空格分隔)作为JVM将传递给应用程序的命令行参数。-这些参数可以用来指定运行应用程序的选项(例如文件名)-这就是为什么在main中有一个名为String[] args的参数

参考资料:Java™如何编程(早期对象),第十版

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