Why is the Java main method static?

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

    Let's simply pretend, that static would not be required as the application entry point.

    An application class would then look like this:

    class MyApplication {
        public MyApplication(){
            // Some init code here
        }
        public void main(String[] args){
            // real application code here
        }
    }
    

    The distinction between constructor code and main method is necessary because in OO speak a constructor shall only make sure, that an instance is initialized properly. After initialization, the instance can be used for the intended "service". Putting the complete application code into the constructor would spoil that.

    So this approach would force three different contracts upon the application:

    • There must be a default constructor. Otherwise, the JVM would not know which constructor to call and what parameters should be provided.
    • There must be a main method1. Ok, this is not surprising.
    • The class must not be abstract. Otherwise, the JVM could not instantiate it.

    The static approach on the other hand only requires one contract:

    • There must be a main method1.

    Here neither abstract nor multiple constructors matters.

    Since Java was designed to be a simple language for the user it is not surprising that also the application entry point has been designed in a simple way using one contract and not in a complex way using three independent and brittle contracts.

    Please note: This argument is not about simplicity inside the JVM or inside the JRE. This argument is about simplicity for the user.


    1Here the complete signature counts as only one contract.

提交回复
热议问题