Why am I allowed to instantiate fields in the class scope but not allowed to call methods on those fields?
public class MethodInFieldTest {
List<Object> list = new ArrayList<>();
// compilation error
// list.add(new Object());
// Compiles just fine, how I usually do it
{
list.add(new Object());
}
// compilation error
// addObject();
public void addObject() {
list.add(new Object());
}
//usual way of handling this
//constructor one
public MethodInFieldTest(... stuff) {
list.add(new Object());
}
//constructor two
public MethodInFieldTest(..) {
list.add(new Object());
}
//etc
//...
//ugly way of doing it
// List<Object> list = new ArrayList<>(Arrays.asList(new Object[]{new Object(), new Object()}));
public static void main(String[] args) {
System.out.println(new MethodInFieldTest().list);
}
}
I often find it makes sense to for instance start a list with some default values and if I have multiple constructors in my class I have to add the default values in the constructors or use the ugly way marked below in the code. The "ugly" way works for lists but for other objects that need a default state for my class (a state not provided by the objects constructor) I have to use private helper methods. I wonder why I can't just do it in the class field, not necessarily a huge inconvenience but I am curious as to why.