We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Confusion initializing objects...
Page Index Toggle Pages: 1
Confusion initializing objects... (Read 217 times)
Confusion initializing objects...
Dec 8th, 2008, 7:00pm
 
I'm trying to grasp how OOP work.  I've ran into a confusion.  Take the following code from a tutorial page:
Code:
void setup()
{
size(200, 200);
framerate(25);

myBalls = new Ball[33]; // creating an (empty) array with a
// capacity of 33 elements of type Ball

for (int i = 0; i < 33; i++) // iterating 33 times
{
myBalls[i] = new Ball(); // populating the array
// with new Ball objects

myBalls[i].x = random(0, 200);
myBalls[i].y = random(0, 200);
}
}


my confusion is with this line.  I don't see why it's necessary:
Code:
    myBalls[i] = new Ball(); 



this seems redundant to me since the ball objects are already initialized earlier in the setup with this line:
Code:
 myBalls = new Ball[33]; 



Am I missing something?
Re: Confusion initializing objects...
Reply #1 - Dec 8th, 2008, 8:08pm
 
myBalls = new Ball[33];  just says that myBalls can hold 33 balls, but doesn't initialise them, it's just defining the size of it.

myBalls[i] = new Ball();  actually creates a ball object and assigns it to slot 'i' in the myBalls array.
Re: Confusion initializing objects...
Reply #2 - Dec 8th, 2008, 11:18pm
 
A concept that seems to trip lot of beginners... I can understand that, coming from the C world, where defining an array of objects allocates the number of bytes of the object multiplied by the number of slots.

But Java, in new Ball[33], only allocate an array of references to objects, these references being null until we make them point to real objects, created classically with new Ball().

The first new allocates the array, the second one creates the object (maybe with constructor parameters, etc.).

What is confusing too is that for primitive types, new int[42] or new double[99] actually allocate all is needed...
Page Index Toggle Pages: 1