HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Why is the Java main method static?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
javawhythemethodmainstatic

Problem

The method signature of a Java mainmethod is:

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


Is there a reason why this method must be static?

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#146576, score: 354

Revisions (0)

No revisions yet.