Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
c++、c#和Java中的主要方法是静态的。
这是因为它们可以被运行时引擎调用,而无需实例化任何对象,然后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程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。
最近,类似的问题也出现在了程序员网站上。SE
为什么在Java和c#中使用静态主方法,而不是构造函数? 从主要或次要来源中寻找一个明确的答案,为什么(特别是)Java和c#决定将静态方法作为它们的入口点-而不是通过应用程序类的实例表示应用程序实例,入口点是一个适当的构造函数?
公认的答案是,
In Java, the reason of public static void main(String[] args) is that Gosling wanted the code written by someone experienced in C (not in Java) to be executed by someone used to running PostScript on NeWS For C#, the reasoning is transitively similar so to speak. Language designers kept the program entry point syntax familiar for programmers coming from Java. As C# architect Anders Hejlsberg puts it, ...our approach with C# has simply been to offer an alternative... to Java programmers... ...
Main()是静态的,因为;在应用程序生命周期的这一点上,应用程序堆栈本质上是过程化的,因为还没有实例化对象。
这是一个干净的石板。您的应用程序此时正在运行,即使没有声明任何对象(请记住,有过程性和OO编码模式)。作为开发人员,通过创建对象的实例并依赖于在其中编译的代码,将应用程序转换为面向对象的解决方案。
面向对象的优点有几百万个显而易见的理由。然而,大多数VB开发人员在代码中经常使用“goto”这样的关键字的日子已经一去不复返了。“goto”是VB中的一个过程命令,它被OO对应的方法调用所取代。
您还可以将静态入口点(main)视为纯粹的自由。如果Java足够不同,可以实例化一个对象,并在运行时只向你呈现该实例,那么你就别无选择,只能编写一个过程化应用程序。对于Java来说,这听起来可能难以想象,但可能有许多场景都需要过程化方法。
这可能是一个非常晦涩的回答。记住,“类”只是一个相互关联的代码的集合。“实例”是这个类的一个孤立的、活生生的、自主的代。
让我用更简单的方式来解释这些事情:
public static void main(String args[])
除了applet,所有Java应用程序都从main()开始执行。
关键字public是一个访问修饰符,允许从类外部调用成员。
使用Static是因为它允许调用main()而不必实例化该类的特定实例。
Void表示main()不返回任何值。