Computer Science Canada

Is it possible to use an ARRAY OF CLASSES?

Author:  Russ355 [ Mon May 23, 2005 11:27 pm ]
Post subject:  Is it possible to use an ARRAY OF CLASSES?

I have a very simple question: Is it possible to use an array of classes? For example, I have created a Car class with the constructor (Color c). Could I make an array to make this easier?

I tried using
Car c [];
c=new Car[100](Color.red)
But this does not work.

Please help me out

Author:  wtd [ Mon May 23, 2005 11:42 pm ]
Post subject: 

Well, the array would be declared as:

Java:
Car[] c;


Since we're declaring an array of Car objects that just happens to be named "c".

Now, when you allocate the array you'd write it as:

Java:
c = new Car[100];


Which allocates space for 100 Car objects, but not the objects themselves. Of course, this need not be two lines of code.

Java:
Car[] c = new Car[100];


Now, to make all of those red...

Java:
for (int i = 0; i < 100; i++)
{
   c[i] = new Car(Color.red);
}


: