Java beginner here who is terribly confused as to why
1) this is valid:
public class MyArrayOfObjects {
MyArrayOfObjects[] myArray = new MyArrayOfObjects[5];
void InstantiateElements (){
myArray[0] = new MyArrayOfObjects();
}
}
2) while this is not:
public class MyArrayOfObjects {
MyArrayOfObjects[] myArray = new MyArrayOfObjects[5];
myArray[0] = new MyArrayOfObjects();
}
from my understanding, each element of the array of objects is instantiating a MyArrayOfObjects object. So why does option 1 work while 2 does not?
Statements other than variable declarations must occur in:
In your second block of code, the statement assigning a value to the first element of the array is not a variable declaration, so it can’t occur directly in the class.
As for why Java is designed this way – to my mind it just makes things simpler. You should put logic to be executed as part of initialization into a constructor. (I would generally try to avoid initializer blocks as well, as it’s easy to forget about them when debugging.)
From section 8.1.6 of the Java Language Specification: