Just started learning Java. Why is the main() inside of a class?

橙三吉。 提交于 2020-01-11 07:07:21

问题


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 called Test.




回答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.



来源:https://stackoverflow.com/questions/28116374/just-started-learning-java-why-is-the-main-inside-of-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!