Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I allow a class to construct other classes when those other classes are passed in by the user?
    text
    copied!<p>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.</p> <pre><code> public class Population{ private List&lt;Individual&gt; 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{ ... } </code></pre> <p>I would like to be able to make a call like <code>population.addIndividualsOfType(HappyIndividual)</code></p> <p>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.</p> <p>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. </p> <p>I feel like this should be very easy, but I'm having trouble. Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload