Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
在Java中声明为静态的任何方法都属于类本身。 同样,特定类的静态方法只能通过引用类Class_name.method_name();
因此,在访问静态方法之前不需要实例化类。
因此main()方法被声明为静态的,这样就可以在不创建该类对象的情况下访问它。
因为我们用存在main方法的类名来保存程序(或者从程序开始执行的地方开始,适用于没有main()方法()的类(高级级别))。所以通过上面提到的方法:
Class_name.method_name();
可以访问主方法。
简而言之,当程序被编译时,它会在类中搜索main()方法,其String参数如下:main(String args[])。由于在开始时它没有实例化该类的作用域,因此main()方法被声明为静态的。
其他回答
因为静态成员不是任何特定类的一部分,而且主方法不需要创建它的Object,但仍然可以引用所有其他类。
基本上,我们将这些数据成员和成员函数设置为STATIC,它们不执行任何与对象相关的任务。对于main方法,我们将其设置为STATIC,因为它与object无关,因为无论我们是否创建对象,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.
这只是惯例。事实上,甚至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和static,它不能返回任何值 值,并且它必须接受String数组作为参数。默认情况下, 第一个非选项参数是要调用的类的名称。 应该使用完全限定的类名。如果-jar选项为 指定后,第一个非选项参数是JAR存档的名称 类包含应用程序的类和资源文件 由Main-Class manifest头指示的启动类。
http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#description