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

查看:26
本文介绍了为什么 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天全站免登陆