Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
static -当JVM调用主方法时,被调用的类不存在对象,因此它必须有静态方法来允许从类调用。
其他回答
如果不是,如果有多个构造函数,应该使用哪个构造函数?
在Java语言规范中有更多关于Java程序初始化和执行的信息。
否则,它将需要一个对象的实例来执行。但是它必须从头开始调用,而不是首先构造对象,因为它通常是main()函数(bootstrap)的任务,解析参数并构造对象,通常是通过使用这些参数/程序参数。
public static void main(String args[])是什么意思?
public is an access specifier meaning anyone can access/invoke it such as JVM(Java Virtual Machine. static allows main() to be called before an object of the class has been created. This is neccesary because main() is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class. class demo { private int length; private static int breadth; void output(){ length=5; System.out.println(length); } static void staticOutput(){ breadth=10; System.out.println(breadth); } public static void main(String args[]){ demo d1=new demo(); d1.output(); // Note here output() function is not static so here // we need to create object staticOutput(); // Note here staticOutput() function is static so here // we needn't to create object Similar is the case with main /* Although: demo.staticOutput(); Works fine d1.staticOutput(); Works fine */ } } Similarly, we use static sometime for user defined methods so that we need not to make objects. void indicates that the main() method being declared does not return a value. String[] args specifies the only parameter in the main() method. args - a parameter which contains an array of objects of class type String.
为什么公共静态无效主(字符串[]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);
... ...
static -当JVM调用主方法时,被调用的类不存在对象,因此它必须有静态方法来允许从类调用。