Java主方法的方法签名是:

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

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


当前回答

这只是惯例。事实上,甚至main()的名称和传入的参数都是纯粹的约定。

当您运行Java .exe(或Windows上的javaw.exe)时,真正发生的是几个Java本机接口(JNI)调用。这些调用加载的DLL是真正的JVM(没错,java.exe不是JVM)。JNI是我们用来连接虚拟机世界和C、c++等语言世界的工具。反过来也是对的——不使用JNI是不可能让JVM运行的(至少据我所知)。

基本上,java.exe是一个超级简单的C应用程序,它解析命令行,在JVM中创建一个新的String数组来保存这些参数,解析出您指定的包含main()的类名,使用JNI调用查找main()方法本身,然后调用main()方法,将新创建的字符串数组作为参数传入。这非常非常类似于您从Java中使用反射时所做的事情——它只是使用了令人混淆的命名本机函数调用。

编写自己版本的java.exe(源代码随JDK一起分发)并让它做一些完全不同的事情是完全合法的。事实上,这正是我们对所有基于java的应用程序所做的。

我们的每个Java应用程序都有自己的启动器。我们这样做主要是为了得到我们自己的图标和进程名,但在其他情况下,当我们想做一些常规的main()调用之外的事情来让事情继续进行时,它也很方便(例如,在一种情况下,我们正在进行COM互操作性,我们实际上将COM句柄传递给main()而不是字符串数组)。

So, long and short: the reason it is static is b/c that's convenient. The reason it's called 'main' is that it had to be something, and main() is what they did in the old days of C (and in those days, the name of the function was important). I suppose that java.exe could have allowed you to just specify a fully qualified main method name, instead of just the class (java com.mycompany.Foo.someSpecialMain) - but that just makes it harder on IDEs to auto-detect the 'launchable' classes in a project.

其他回答

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程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。

c++、c#和Java中的主要方法是静态的。

这是因为它们可以被运行时引擎调用,而无需实例化任何对象,然后main主体中的代码将完成其余的工作。

主方法总是需要是静态的,因为在运行时JVM不会创建任何对象来调用主方法,正如我们所知,在java中静态方法是唯一可以使用类名调用的方法,所以主方法总是需要是静态的。

更多信息请访问这个视频:https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be

public关键字是一个访问修饰符,它允许程序员进行控制 类成员的可见性。当类成员前面有public时,则 成员可以由声明它的类之外的代码访问。

public的反义词是private,它防止成员被定义在类外部的代码使用。

在这种情况下,main()必须声明为public,因为必须调用它 当程序启动时,由其类之外的代码执行。

关键字static允许 Main()被调用,而不必实例化类的特定实例。这是必要的,因为Java解释器在创建任何对象之前调用main()。

关键字void只是告诉编译器main()不返回值。