Why is the Java main method static?

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

    The public keyword is an access modifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared.

    The opposite of public is private, which prevents a member from being used by code defined outside of its class.

    In this case, main() must be declared as public, since it must be called by code outside of its class when the program is started.

    The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is necessary since main() is called by the Java interpreter before any objects are made.

    The keyword void simply tells the compiler that main() does not return a value.

提交回复
热议问题