Why is the Java main method static?

前端 未结 30 2140
离开以前
离开以前 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:11

    When you execute the Java Virtual Machine (JVM) with the java command,

    java ClassName argument1 argument2 ...
    

    When you execute your application, you specify its class name as an argument to the java command, as above

    the JVM attempts to invoke the main method of the class you specify

    —at this point, no objects of the class have been created.

    Declaring main as static allows the JVM to invoke main without creating an instance of the class.

    let's back to the command

    ClassName is a command-line argument to the JVM that tells it which class to execute. Following the ClassName, you can also specify a list of Strings (separated by spaces) as command-line arguments that the JVM will pass to your application. -Such arguments might be used to specify options (e.g., a filename) to run the application- this is why there is a parameter called String[] args in the main

    References:Java™ How To Program (Early Objects), Tenth Edition

提交回复
热议问题