为什么Java main方法是静态的? [英] Why is the Java main method static?

查看:142
本文介绍了为什么Java main方法是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java main() 方法的方法签名是:

The method signature of a Java main() method is:

public static void main(String[] args){
    ...
}

此方法是否有理由保持静态?

推荐答案

方法是静态的,否则会有歧义:应该调用哪个构造函数?特别是如果你的类看起来像这样:

The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:

public class JavaClass{
  protected JavaClass(int x){}
  public void main(String[] args){
  }
}

JVM应该调用 new JavaClass(int)吗?应该为 x 传递什么?

Should the JVM call new JavaClass(int)? What should it pass for x?

如果没有,JVM是否应实例化 JavaClass 没有运行任何构造函数方法?我认为它不应该,因为这将特殊情况下你的整个类 - 有时你有一个尚未初始化的实例,你必须在每个可以调用的方法中检查它。

If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.

有很多边缘情况和含糊之处使得JVM必须在调用入口点之前实例化一个类。这就是为什么 main 是静态的。

There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why main is static.

我不知道为什么 main 总是标记为 public

I have no idea why main is always marked public though.

这篇关于为什么Java main方法是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆