Java主方法的方法签名是:

public static void main(String[] args) {
    ...
}

为什么这个方法必须是静态的?


当前回答

使用Java命令运行Java虚拟机(JVM)时,

java ClassName argument1 argument2 ...

当您执行您的应用程序时,您指定它的类名作为java命令的参数,如上所述

JVM尝试调用您指定的类的主方法

-在这一点上,类的对象还没有被创建。 将main声明为静态允许JVM在不创建的情况下调用main 类的实例。

让我们回到命令

ClassName是JVM的命令行参数,它告诉JVM要执行哪个类。在ClassName之后,您还可以指定一个字符串列表(由空格分隔)作为JVM将传递给应用程序的命令行参数。-这些参数可以用来指定运行应用程序的选项(例如文件名)-这就是为什么在main中有一个名为String[] args的参数

参考资料:Java™如何编程(早期对象),第十版

其他回答

Main()是静态的,因为;在应用程序生命周期的这一点上,应用程序堆栈本质上是过程化的,因为还没有实例化对象。

这是一个干净的石板。您的应用程序此时正在运行,即使没有声明任何对象(请记住,有过程性和OO编码模式)。作为开发人员,通过创建对象的实例并依赖于在其中编译的代码,将应用程序转换为面向对象的解决方案。

面向对象的优点有几百万个显而易见的理由。然而,大多数VB开发人员在代码中经常使用“goto”这样的关键字的日子已经一去不复返了。“goto”是VB中的一个过程命令,它被OO对应的方法调用所取代。

您还可以将静态入口点(main)视为纯粹的自由。如果Java足够不同,可以实例化一个对象,并在运行时只向你呈现该实例,那么你就别无选择,只能编写一个过程化应用程序。对于Java来说,这听起来可能难以想象,但可能有许多场景都需要过程化方法。

这可能是一个非常晦涩的回答。记住,“类”只是一个相互关联的代码的集合。“实例”是这个类的一个孤立的、活生生的、自主的代。

Static表示该方法是类方法。并且调用时不需要任何类的对象。

这背后的原因很简单,因为对象不需要调用静态方法,如果它是非静态方法,java虚拟机先创建对象,然后调用main()方法,这将导致额外的内存分配问题。

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.

各种类型的applet、midlet、servlet和bean被构造,然后在它们上调用生命周期方法。调用main是对主类所做的全部工作,因此不需要在被多次调用的对象中保存状态。将main固定在另一个类上是很正常的(尽管这不是一个好主意),这将妨碍使用类创建main对象。