Why do you need a main method to use class methods in a class?

I can do it:

import java.util.ArrayList;

public class Array {

    public static void main(String args[]){

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

    myList.add("S");

    }
}

      

However, I CAN'T do this:

import java.util.ArrayList;

public class Array {

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

    myList.add("S");


}

      

Why should I include the main method?

+3


source to share


2 answers


Because Java classes are made up of methods and blocks. You cannot have an expression like

myList.add("S");

      



Finally, your application requires an entry point , and the Java virtual machine starts with a call main()

as described in JLS -12.1.4. InvokeTest.main

Finally, after completing the initialization for the class Test

(for which there could be another subsequent loading, binding and initialization), the method is called main

of Test

.

The main feature of the method must be declared public

, static

and void

. It must specify a formal parameter ( Β§8.4.1 ) of which the declared type is an array String

.

+13


source


You need it main

because that is the convention that the program starts with. The program cannot know what the class is doing or why the class exists, so it only works when you use it internally main

, considering it as a starting point.



+4


source







All Articles