Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
这只是一种惯例。JVM当然可以处理非静态的主方法,如果这是惯例的话。毕竟,您可以在类上定义静态初始化器,并在到达main()方法之前实例化无数对象。
其他回答
静态方法不需要任何对象。它直接运行,所以main直接运行。
因为静态成员不是任何特定类的一部分,而且主方法不需要创建它的Object,但仍然可以引用所有其他类。
各种类型的applet、midlet、servlet和bean被构造,然后在它们上调用生命周期方法。调用main是对主类所做的全部工作,因此不需要在被多次调用的对象中保存状态。将main固定在另一个类上是很正常的(尽管这不是一个好主意),这将妨碍使用类创建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.
这是一个经常被问到的问题,为什么main()在Java中是静态的。
答:我们知道在Java中,JVM从main()开始执行。当JVM执行main()时,包含main()的类不会被实例化,因此我们不能在没有引用它的对象的情况下调用非静态方法。因此,为了调用它,我们将其设置为静态的,因此类装入器将所有静态方法装入JVM上下文内存空间中,JVM可以从那里直接调用它们。