问题
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 methodmain
ofTest
is invoked.The method main must be declared
public
,static
, andvoid
. It must specify a formal parameter (§8.4.1) whose declared type is array ofString
.
回答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