Say you have a class Population and Population makes an internal List of Individuals. The user wants to pass an unconstructed Individual subclass to Population and let Population do the work of constructing these, whatever subclass was passed.
public class Population{
private List<Individual> indiList = new ArrayList(25);
/*I know this won't work for multiple reasons, but shows the idea*/
public void addIndividualsOfType(Individual individual){
for (ListIterator it = indiList.listIterator(); it.hasNext(); ){
it.next()
it.add(individual.construct(param1, param2, param3);
}
}
}
public abstract class Individual{
SomeType param1;
...
public Individual(SomeType param1, SomeType param2, SomeType param3){
this.param1 = param1;
...
}
}
public class HappyIndividual extends Individual{
...
}
public class SadIndividual extends Individual{
...
}
I would like to be able to make a call like population.addIndividualsOfType(HappyIndividual)
Obviously, this code will not work for many reasons (like passing an uninstantiated class). I am just trying to illustrate the idea of what I want to do, this is not a question of why the above code does not work. I know it won't work, which is why I can't figure out how one would do such a thing.
I have been messing around with Builders and Static Factory Methods all day. The problem is that we are talking subclasses here. Subclasses don't play well with Static. If I give Individual a static factory method, then I end up creating Individuals, not HappyIndividuals. Similar problems occur with Builder. I also want to keep this not overly complex.
I feel like this should be very easy, but I'm having trouble. Thanks.