I'm learning Java and I noticed that the main()
is put inside of a class. Why? I don't consider my main()
to be a member of any object. So please tell me how I can get around this.
问题:
回答1:
I don't consider my
main()
to be a member of any object.
It's not since it's a static
method. It does not belong to any object but to the class itself.
Aside from that, all methods, including main
must be defined in classes.
More generally, a class is the smallest unit in compiled Java code and contains both information on instances of the class and behavioral code that runs by itself (e.g. the main
method).
回答2:
You must put the main()
in a class. And, it must be static
(which means it is not a member of any Object
). When you launch the Java Runtime Environment (JRE) it will load that class and invoke the main()
.
This is covered by JLS-12.1 - Java Virtual Machine Startup which says in part,
The Java Virtual Machine starts execution by invoking the method
main
of some specified class, passing it a single argument, which is an array of strings. In the examples in this specification, this first class is typically calledTest
.
回答3:
By nature, Java is highly object oriented. So everything must be encapsulated within a class. All methods must be placed inside of a class. However, the main() is different. There can only be one main function in a class and it must always be static, meaning it is not part of an object and there is only one instance of it. When a java application is executed, the JRE will look for the main class (i.e. the class containing the main function). main() is where the execution starts. But due to the very nature of OO, it must be placed in a class. You can say that this is simply because of the skeletal structure of java. No other reason in particular.