Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
因为静态成员不是任何特定类的一部分,而且主方法不需要创建它的Object,但仍然可以引用所有其他类。
其他回答
这只是一种惯例,但可能比另一种更方便。使用静态主程序,调用Java程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。
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.
否则,它将需要一个对象的实例来执行。但是它必须从头开始调用,而不是首先构造对象,因为它通常是main()函数(bootstrap)的任务,解析参数并构造对象,通常是通过使用这些参数/程序参数。
由于程序从main()和开始执行,java是纯面向对象的程序,其中对象在main()中声明,这意味着main()在对象创建之前被调用,因此如果main()是非静态的,那么就需要一个对象,因为静态意味着不需要对象..........
为什么公共静态无效主(字符串[]args) ?
这就是Java语言和Java虚拟机是如何设计和编写的。
Oracle Java语言规范
请参阅第12章执行- 12.1.4节调用Test.main:
最后,在完成Test类的初始化之后(在此期间可能发生了其他相应的加载、链接和初始化),调用Test的main方法。 方法main必须声明为public、static和void。它必须接受一个字符串数组的参数。此方法可以声明为任意一种 public static void main(String[] args) 或 public static void mainargs)
Oracle Java虚拟机规范
请参阅第2章Java编程语言概念-第2.17节执行:
Java虚拟机通过调用某个指定类的main方法并向其传递一个参数(字符串数组)来开始执行。这将导致指定的类被加载(§2.17.2),链接(§2.17.3)到它使用的其他类型,并初始化(§2.17.4)。方法main必须声明为public、static和void。
Oracle OpenJDK源代码
下载并提取jar源代码,看看JVM是如何编写的,查看../launcher/java. C,其中包含java [-options] class [args…]命令背后的原生C代码:
/*
* Get the application's main class.
* ... ...
*/
if (jarfile != 0) {
mainClassName = GetMainClassName(env, jarfile);
... ...
mainClass = LoadClass(env, classname);
if(mainClass == NULL) { /* exception occured */
... ...
/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
"([Ljava/lang/String;)V");
... ...
{ /* Make sure the main method is public */
jint mods;
jmethodID mid;
jobject obj = (*env)->ToReflectedMethod(env, mainClass,
mainID, JNI_TRUE);
... ...
/* Build argument array */
mainArgs = NewPlatformStringArray(env, argv, argc);
if (mainArgs == NULL) {
ReportExceptionDescription(env);
goto leave;
}
/* Invoke main method. */
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
... ...