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)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值