In a Java class where you normally declare/define instance variables, I would like to have an ArrayList
as one of the instance variables and initialize it with some elements to start out with. One way of doing this is declare the ArrayList
and initialize it in a constructor. However, I am wondering why it is illegal to initialize the value outside the constructor. For example,
public class Test {
// some instance variables...
private ArrayList<String> list = new ArrayList<String>();
list.add("asdf");
// methods here...
}
So I get that this is illegal. But why exactly is this illegal?