Initializing an Array of Objects
NOTE: This is more of a post asking for a little clarification, rather than one asking for help.
Java does not seem to actually create any objects when you define an array specifically of objects, unlike if it was an array of primitives which are initialized to their type's default. The following code demonstrates what I'm getting at:
public class GridSquare
private int x, y, width, height;
public GridSquare() //Constructor
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
public void setGridLocation(int newX, int newY, int newWidth, int newHeight)
this.x = newX;
this.y = newY;
this.width = newWidth;
this.height = newHeight;
public class Map
GridSquare gridSquares = new GridSquare; //This only creates a 10 by 10 array of Null GridSquare objects
public Map() //Constructor
gridSquares.setGridLocation(50,50,50,50); //A test location that shows all gridSquares locations are Null
Now, I've done a fair share of Google searching to reach this conclusion, and the answer I seem to get is that I should (separately) initialize every single array cell with the new command, such as described by these sources:
Array of objects initialization Problem - Java - Forums at ProgrammersHeaven.com
Explain how to initialize an array of objects
This seems like a roundabout way to accomplish what I would think Java could handle on its own. Is there any particular reason that Java is unable to actually create an object for each cell and reference it? With a proper Constructor written for the object in the array so that the proper data gets loaded, I'd imagine you could skip all the extra work.
Re: Initializing an Array of Objects
That is true. How would java know how to call the class's constructor to create the objects? It leaves the slots in the array with null values. Even if it would use a default constructor, that could be a lot of useless work if the user wants meaningful data in the array and has to assign values with data to all the slots.
Java does not seem to actually create any objects when you define an array
Yes that is how you have to it.
I should (separately) initialize every single array cell with the new command,