为什么需要 main 方法才能在类中使用 arraylist 方法? [英] Why need main method in order to use arraylist methods in the class?

查看:38
本文介绍了为什么需要 main 方法才能在类中使用 arraylist 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以做到:

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");


}

为什么我必须包含 main 方法?

推荐答案

因为 Java 类由方法和块组成.你不能有像

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

myList.add("S");

最后,您的应用程序需要一个入口点,Java 虚拟机通过调用main()JLS-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的初始化完成后(在此期间可能发生了其他后续的加载、链接和初始化),的方法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.

方法 main 必须声明为 publicstaticvoid.它必须指定一个形式参数(§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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆