Java的main()方法

你是否有过疑问,为什么在Java中main方法必须是公有,静态的并且没有返回值?

为什么是公有的(public)?

Big question and perhaps most difficult too. I tried hard to find a good reason for this question in all good learning material in my reach, but nothing proved enough. So, my analysis says (like many others): main method is public so that it can be accessible everywhere and to every object which may desire to use it for launching the application. Here, i am not saying that JDK/JRE had similar reasons because java.exe or javaw.exe(for windows) use Java Native Interface (JNI) calls to invoke method, so they can have invoked it either way irrespective of any access modifier.

Second way to answer this is another question, why not public? All methods and constructors in java have some access modifier. main() method also need one. There is no reason why it should not be public, and be any other modifier(default/protected/private).

为什么是静态的(static)?

我们先假设main方法不是静态的,那我们diao调用时就一定需要一个实例。

我们都知道Java的构造方法可以重载,那么现在

Now, which one should be used and from where the parameters for overloaded constructors will come. These are just more difficult questions, which helped Java designers to make up their mind and to have main method as static.

为什么返回值是空(void)?

为什么不能为空?其他方法需要调用main方法,并没有。因此,main方法不需要返回任何值给真正调用的JVM。它buxu不需要任何返回值。

只有一种情况程序需要返回:是否有异常。这通常通过System.exit(int)方法返回。rugu如果值为非0,则是异常情况。

调用main方法后:

当你运行了java.exe,就会调用一堆Java Native Interface(JNI)。

你可能感兴趣的:(Java)