为什么需要main方法才能在类中使用arraylist方法? [英] Why need main method in order to use arraylist methods in the class?
问题描述
我可以这样做:
import java.util.ArrayList;
public class Array {
public static void main(String args[]){
ArrayList<String> myList = new ArrayList<String>();
myList.add("S");
}
}
但是我不能这样做:
import java.util.ArrayList;
public class Array {
ArrayList<String> myList = new ArrayList<String>();
myList.add("S");
}
为什么必须包含主要方法?
推荐答案
因为Java类由方法和块组成.您不能有像这样的原始语句
Because Java classes consist of methods and blocks. You can't have a raw statement like
myList.add("S");
最后,您的应用程序需要入口点,并且Java虚拟机通过调用开始 JLS记录的main()
-12.1.4.调用Test.main
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
最后,在完成对类
Test
的初始化之后(在此期间可能发生了其他相应的装载,链接和初始化),将调用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.
必须将方法main声明为public
,static
和void
.它必须指定一个正式参数( §8.4.1),其声明的类型为String
的数组.
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
.
这篇关于为什么需要main方法才能在类中使用arraylist方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!