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 › how to create multiple instances of a class
Page Index Toggle Pages: 1
how to create multiple instances of a class? (Read 981 times)
how to create multiple instances of a class?
Apr 22nd, 2010, 12:37pm
 
Is it posible to create multiple instances of a class at once using an automated way? For example lets say i have made a class drawing a flying bird. Is it possible to make 100 instances of this class? Thank you very much!
Re: how to create multiple instances of a class?
Reply #1 - Apr 22nd, 2010, 12:47pm
 
Sure.

The unsophisticated way allocates a distinct object name for each bird:

Code:

Bird myBird1 = new Bird();
Bird myBird2 = new Bird();
Bird myBird3 = new Bird();


The slightly-more-sophisticated way, which lets you adjust the number of birds in your sketch fairly easily with small code edits:

Code:

Bird[] myBirds;

myBirds = new Bird[100];

for (int i = 0; i < 100; ++i) {
myBirds[i] = new Bird();
}


The slightly-more-sophisticated-than-that way, which lets your sketch handle a number of birds that you don't know as you're writing:

Code:

List<Bird> myBirdList;

myBirdList = new ArrayList<Bird>();

for (int i = 0; i < 100; ++i) {
Bird freshBird = new Bird();
myBirdList.add(freshBird);
}

Re: how to create multiple instances of a class?
Reply #2 - Apr 22nd, 2010, 12:57pm
 
you are too fast!  Shocked
Re: how to create multiple instances of a class?
Reply #3 - Apr 22nd, 2010, 2:54pm
 
What you're wanting to do is exactly the reason that "classes" exist at all. I'm not sure how you could know what a class is, and not know how to instantiate instances of said class.

To understand the basics of object-oriented programming, I recommend taking a look here:

http://processing.org/learning/objects/
Re: how to create multiple instances of a class?
Reply #4 - Apr 22nd, 2010, 3:20pm
 
I was looking for an automated way to do it, this was what i didn't know. I knew how to do it manualy but not in a for(...){...}
Page Index Toggle Pages: 1