Given a collection of one class, get the objects of its child class...

First, I have a Fleet, which contains a collection of Ships (ArrayList) of all different types (classes that extend Ship). Next, I have a Celestial object, which could be one of several different types (classes that extend Celestial).

Some types of Ships can harvest resources from one and only one type of Celestial each. For example, an OreShip (extends Ship) and only an OreShip can harvest from and only from an AsteroidBelt (extends Celestial). Furthermore, not all types of Ships can harvest (those that can do so implement the interface Harvests) and not all types of Celestials are harvestable (those that are implement the interface Harvestable).

Now, here is the problem. If the Fleet has access to a Celestial body that is an AsteroidBelt and contains at least one OreShip, I want to be able to order the Fleet to make its OreShips, and only the OreShips, harvest from the AsteroidBelt. How can I do this, preferably without a massive if/else switch, given the ArrayList?

I would make it like this,
your celestial objects have a type or types of resources they provide(ORE, IRON what ever)
then on your ships which can harvest you have a method which asks bollean canHarvestType(Type[] types)
then you can easily filter out the ships which can harvest from the celestial object.


Celestial c;
Collection<Ship> ships;

//some pseudo linq/sql statement
from s in ships
where s implements Harvest
where s.canHarvetType(c.getTypes())

What Danny02 said – it’s spot on. Notice that you don’t really even need to subclass when you do it like that. You might subclass for other reasons, but your app logic would still use capabilities defined on interfaces, not the much less flexible arrangement of super/subclasses.

For a more exotic arrangement, this is also the use case of entity systems, selecting a subset from some global list of entities. Not endorsing that approach, just saying that’s a possibility.