Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
这只是一种惯例,但可能比另一种更方便。使用静态主程序,调用Java程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。
其他回答
来自java.sun.com(网站上有更多信息):
主要方法是静态的,以使Java VM解释器能够在不首先创建控件类实例的情况下启动类。控件类的实例在程序启动后在main方法中创建。
我的理解一直很简单,就像任何静态方法一样,可以在不创建相关类的实例的情况下调用主方法,允许它在程序中的任何其他方法之前运行。如果它不是静态的,你就必须在调用它之前实例化一个对象——这就产生了一个“先有鸡还是先有蛋”的问题,因为main方法通常是你在程序开始时用来实例化对象的。
The static key word in the main method is used because there isn't any instantiation that take place in the main method. But object is constructed rather than invocation as a result we use the static key word in the main method. In jvm context memory is created when class loads into it.And all static members are present in that memory. if we make the main static now it will be in memory and can be accessible to jvm (class.main(..)) so we can call the main method with out need of even need for heap been created.
static -当JVM调用主方法时,被调用的类不存在对象,因此它必须有静态方法来允许从类调用。
这只是惯例。事实上,甚至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.
该方法是静态的,否则就会产生歧义:应该调用哪个构造函数?特别是如果你的类是这样的:
public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}
JVM是否应该调用新的JavaClass(int)?x应该通过什么?
如果不是,JVM是否应该实例化JavaClass而不运行任何构造函数方法?我认为不应该这样,因为那样会使你的整个类出现特殊情况——有时你有一个没有初始化的实例,你必须在每个可能被调用的方法中检查它。
在调用入口点之前,JVM必须实例化一个类,这有太多的边缘情况和模糊性,因此没有意义。这就是为什么main是静态的。
我不知道为什么main总是被标记为public。