Why is the Java main method static?

前端 未结 30 2023
离开以前
离开以前 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 02:14

    The protoype public static void main(String[]) is a convention defined in the JLS :

    The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.

    In the JVM specification 5.2. Virtual Machine Start-up we can read:

    The Java virtual machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java virtual machine then links the initial class, initializes it, and invokes the public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java virtual machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.

    Funny thing, in the JVM specification it's not mention that the main method has to be static. But the spec also says that the Java virtual machine perform 2 steps before :

    • links the initial class (5.4. Linking)
    • initializes it (5.5. Initialization)

    Initialization of a class or interface consists of executing its class or interface initialization method.

    In 2.9. Special Methods :

    A class or interface initialization method is defined :

    A class or interface has at most one class or interface initialization method and is initialized (§5.5) by invoking that method. The initialization method of a class or interface has the special name , takes no arguments, and is void.

    And a class or interface initialization method is different from an instance initialization method defined as follow :

    At the level of the Java virtual machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name .

    So the JVM initialize a class or interface initialization method and not an instance initialization method that is actually a constructor. So they don't need to mention that the main method has to be static in the JVM spec because it's implied by the fact that no instance are created before calling the main method.

提交回复
热议问题