开发者

explanation as to why instantiating the elements of an array of objects needs to be done inside a method

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 instantiat开发者_如何学Cing a MyArrayOfObjects object. So why does option 1 work while 2 does not?


myArray[0] = new MyArrayOfObjects(); is a statement – a line of executable code.
Statements can only appear in methods or initializer blocks.

Class definitions can only contain declarations (fields, methods, constructors, inner classes), not statements.
Fields can also have initializers.


Statements other than variable declarations must occur in:

  • Methods
  • Constructors
  • Initializer blocks

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:

A class body may contain declarations of members of the class, that is, fields (§8.3), classes (§8.5), interfaces (§8.5) and methods (§8.4). A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.


You have to put this line:

myArray[0] = new MyArrayOfObjects();

into an constructor. The class body can't contain statements, just declarations.


Not exactly an answer to why, this has been answered already but as an addition. You could initialize your array on declaration with an array initializer:

public class MyArrayOfObjects {

    MyArrayOfObjects[]  foo = new MyArrayOfObjects[] { new MyArrayOfObjects(), null, null, null, null };
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜