common practice for multiple object types in an arraylist?

  • Thread starter Thread starter Tarren
  • Start date Start date
T

Tarren

Hi:

I am writing a public function as part of a class and wanted to inquire as
to what is common practice to the following scenario.

I have a class called CARDEALERSHIP

i have two classes USEDCAR and NEWCAR both of which inherit CAR class

For the dealership, I have a property called INVENTORIEDCARS which returns
an ArrayList

since this inventory contains both USEDCAR objects and NEWCAR objects, would
i have the arraylist have objects of both types?

Then when I call an item in the arraylist, I would have to check the type
and carry out logic based on that?

How have people dealt with a scenario such as this?

Thanks all!
 
If there are many properties (I would think there would be) that USEDCAR and
NEWCAR both share then you might want to create a base class to hold those
properties. Then create those classes inheriting from lets say CAR which is
your base class.

Then you can do the following with INVENTORIEDCARS:

for each poCar as CAR in INVENTORIEDCARS

next

You will be assured (of course if you stored the correct objects) of getting
a list which could contain either USEDCAR or NEWCAR objects.

Now if the difference are not that great between the two classes you might
want to have a class that has all the details of CAR's and have a property
indicating whether the CAR was used or new.

If you cannot do this then within the for each loop above you can check the
typename of the poCar object returned and deal with it as required.

Lloyd Sheen
 
thanks!

Lloyd Sheen said:
If there are many properties (I would think there would be) that USEDCAR and
NEWCAR both share then you might want to create a base class to hold those
properties. Then create those classes inheriting from lets say CAR which is
your base class.

Then you can do the following with INVENTORIEDCARS:

for each poCar as CAR in INVENTORIEDCARS

next

You will be assured (of course if you stored the correct objects) of getting
a list which could contain either USEDCAR or NEWCAR objects.

Now if the difference are not that great between the two classes you might
want to have a class that has all the details of CAR's and have a property
indicating whether the CAR was used or new.

If you cannot do this then within the for each loop above you can check the
typename of the poCar object returned and deal with it as required.

Lloyd Sheen
 
Back
Top