Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
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.
其他回答
基本上,我们将这些数据成员和成员函数设置为STATIC,它们不执行任何与对象相关的任务。对于main方法,我们将其设置为STATIC,因为它与object无关,因为无论我们是否创建对象,main方法总是运行。
public关键字是一个访问修饰符,它允许程序员进行控制 类成员的可见性。当类成员前面有public时,则 成员可以由声明它的类之外的代码访问。
public的反义词是private,它防止成员被定义在类外部的代码使用。
在这种情况下,main()必须声明为public,因为必须调用它 当程序启动时,由其类之外的代码执行。
关键字static允许 Main()被调用,而不必实例化类的特定实例。这是必要的,因为Java解释器在创建任何对象之前调用main()。
关键字void只是告诉编译器main()不返回值。
原型public static void main(String[])是在JLS中定义的约定:
方法main必须声明为public、static和void。它必须指定一个形式形参(§8.4.1),其声明类型为String数组。
在JVM规范5.2中。虚拟机启动我们可以读到:
The Java virtual machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java virtual machine then links the initial class, initializes it, and invokes the public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java virtual machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.
有趣的是,在JVM规范中并没有提到主方法必须是静态的。 但是规范还说Java虚拟机执行以下两个步骤:
链接初始类(5.4。链接) 初始化它。初始化)
类或接口的初始化包括执行类或接口的初始化方法。
在2.9。特殊方法:
定义一个类或接口初始化方法:
一个类或接口最多有一个类或接口初始化方法,并通过调用该方法进行初始化(§5.5)。类或接口的初始化方法具有特殊名称<clinit>,不带参数,且为空。
类或接口初始化方法不同于定义如下的实例初始化方法:
在Java虚拟机级别,每个用Java编程语言(JLS§8.8)编写的构造函数都作为实例初始化方法出现,具有特殊名称<init>。
因此JVM初始化一个类或接口初始化方法,而不是实例初始化方法,后者实际上是一个构造函数。 因此,他们不需要在JVM规范中提到主方法必须是静态的,因为在调用主方法之前不创建实例这一事实暗示了这一点。
各种类型的applet、midlet、servlet和bean被构造,然后在它们上调用生命周期方法。调用main是对主类所做的全部工作,因此不需要在被多次调用的对象中保存状态。将main固定在另一个类上是很正常的(尽管这不是一个好主意),这将妨碍使用类创建main对象。
这只是一种惯例。JVM当然可以处理非静态的主方法,如果这是惯例的话。毕竟,您可以在类上定义静态初始化器,并在到达main()方法之前实例化无数对象。