We are about to switch to a new forum software. Until then we have removed the registration on this forum.
sorry to keep on going on about declaring and initializing statements but in the below example why do we initialize the array at the top (global) and then initialize it again in setup is the the top part Mover[] movers = new Mover[20]; just another way of declaring an array?and if so why would we declare it with the new function
Mover[] movers = new Mover[20];
void setup() {
size(800,200);
for (int i = 0; i < movers.length; i++) {
movers[i] = new Mover();
}
}
void draw() {
background(255);
for (int i = 0; i < movers.length; i++) {
movers[i].update();
movers[i].display();
}
}
Answers
Mover[] movers = new Mover[20];
movers[i] = new Mover();
More detailed attempt explanations:
null
. So when we declareMover[] movers
, movers contains valuenull
.null
is an invalid object reference. So we gotta instantiate a compatible type object and assign it to the variable.null
.null
values.for
loop, w/ its iterator representing current array's index, will have the job done.{}
, in which we choose the initial values for each of its slots:Mover[] movers = { new Mover(), new Mover(), new Mover(), new Mover(), new Mover() };
ok so by reference you mean movers? could we say that in the class section we have built an object of type array and given it a specific array value and in the setup or constructor section we are building each element in the array and giving each element a set of object,primitive or null, values.
it still appears to me as though we still constructing 2 objects when only one will do is there a good reason to do this other than to declare the no of instantiations you want to construct ie Mover[20] or is it just a subjective way the guys who built java use to deal with arrays
Cheers
sorry wrote that just before i saw your more updated explanation reading it now
You're mixing up the array data-structure instantiation & its slot instantiations.
If you need 20 Mover objects, you're gonna need 21 instantiations: The array itself, plus its 20 Mover slots! :P
ok i see so we are declaring and initializing the array itself at the class level as one object and instantiating our 20 other objects that make up the array in setup.
That's right! 1st the structure, then its elements. :D
Only a little extra curiosity: Arrays in Java aren't a class! @-)
Java arrays can only be instantiated and accessed through
[]
. Along the special initialization case w/{}
. b-(i see :) so is this why we have to declare one object as type array at the class level and then access all elements in the array through that object :-/
You can think of the first declaration as making an egg box: it has slots to put eggs, but it is empty. Then, in setup(), you fill the box with eggs...
As said, it is not "initialized twice", these are different operations. One without the other is prone to fail.