Why is the Java main method static?

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

    The true entry point to any application is a static method. If the Java language supported an instance method as the "entry point", then the runtime would need implement it internally as a static method which constructed an instance of the object followed by calling the instance method.

    With that out of the way, I'll examine the rationale for choosing a specific one of the following three options:

    1. A static void main() as we see it today.
    2. An instance method void main() called on a freshly constructed object.
    3. Using the constructor of a type as the entry point (e.g., if the entry class was called Program, then the execution would effectively consist of new Program()).

    Breakdown:

    static void main()

    1. Calls the static constructor of the enclosing class.
    2. Calls the static method main().

    void main()

    1. Calls the static constructor of the enclosing class.
    2. Constructs an instance of the enclosing class by effectively calling new ClassName().
    3. Calls the instance method main().

    new ClassName()

    1. Calls the static constructor of the enclosing class.
    2. Constructs an instance of the class (then does nothing with it and simply returns).

    Rationale:

    I'll go in reverse order for this one.

    Keep in mind that one of the design goals of Java was to emphasize (require when possible) good object-oriented programming practices. In this context, the constructor of an object initializes the object, but should not be responsible for the object's behavior. Therefore, a specification that gave an entry point of new ClassName() would confuse the situation for new Java developers by forcing an exception to the design of an "ideal" constructor on every application.

    By making main() an instance method, the above problem is certainly solved. However, it creates complexity by requiring the specification to list the signature of the entry class's constructor as well as the signature of the main() method.

    In summary, specifying a static void main() creates a specification with the least complexity while adhering to the principle of placing behavior into methods. Considering how straightforward it is to implement a main() method which itself constructs an instance of a class and calls an instance method, there is no real advantage to specifying main() as an instance method.

提交回复
热议问题