Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
在main方法被调用之前,没有对象被实例化。使用static关键字意味着可以在不创建任何对象的情况下调用方法。
其他回答
让我们简单地假设,静态不需要作为应用程序入口点。
一个应用程序类看起来是这样的:
class MyApplication {
public MyApplication(){
// Some init code here
}
public void main(String[] args){
// real application code here
}
}
构造函数代码和主方法之间的区别是必要的,因为在OO中,构造函数只应确保实例被正确初始化。初始化后,实例可以用于预期的“服务”。将完整的应用程序代码放到构造函数中会破坏这一点。
因此,这种方法将在应用程序上强制执行三个不同的契约:
必须有一个默认构造函数。否则,JVM将不知道调用哪个构造函数以及应该提供哪些参数。 必须有一个主要的方法。好吧,这并不奇怪。 类不能是抽象的。否则,JVM无法实例化它。
另一方面,静态方法只需要一个契约:
必须有一个主要的方法。
这里抽象构造函数和多重构造函数都不重要。
由于Java被设计为一种简单的语言,所以应用程序入口点被设计为使用一个简单的契约,而不是使用三个独立而脆弱的契约,这并不奇怪。
请注意:这个参数不是关于JVM或JRE内部的简单性。这个参数是关于用户的简单性。
在这里,完整的签名只能算作一份合同。
这只是一种惯例。JVM当然可以处理非静态的主方法,如果这是惯例的话。毕竟,您可以在类上定义静态初始化器,并在到达main()方法之前实例化无数对象。
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程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。
这只是一个惯例,我们可以在这里看到:
方法必须声明为public和static,它不能返回任何值 值,并且它必须接受String数组作为参数。默认情况下, 第一个非选项参数是要调用的类的名称。 应该使用完全限定的类名。如果-jar选项为 指定后,第一个非选项参数是JAR存档的名称 类包含应用程序的类和资源文件 由Main-Class manifest头指示的启动类。
http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#description