Why is the Java main method static?

前端 未结 30 2172
离开以前
离开以前 2020-11-22 01:41

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

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

Is the

30条回答
  •  逝去的感伤
    2020-11-22 01:56

    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){
      }
    }
    

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

    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.

    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.

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

提交回复
热议问题