Why need main method in order to use arraylist methods in the class?

女生的网名这么多〃 提交于 2020-07-05 11:59:05

问题


I can do this:

import java.util.ArrayList;

public class Array {

    public static void main(String args[]){

    ArrayList<String> myList = new ArrayList<String>();

    myList.add("S");

    }
}

However I CANNOT do this:

import java.util.ArrayList;

public class Array {

    ArrayList<String> myList = new ArrayList<String>();

    myList.add("S");


}

Why I have to include the main method?


回答1:


Because Java classes consist of methods and blocks. You can't have a raw statement like

myList.add("S");

Finally, your application needs an Entry point and the Java Virtual Machine starts by invoking main() as documented by JLS-12.1.4. Invoke Test.main

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.




回答2:


You need main because is the convention from where the program starts. The program cannot know what does or why exist a class so it works only when you using it inside the main by convention it's the starting point.



来源:https://stackoverflow.com/questions/27553538/why-need-main-method-in-order-to-use-arraylist-methods-in-the-class

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