java - How do I add different inner classes to an ArrayList? -
so, i'm building basic program based on warhammer 40k tabletop game credit assignment comp sci class. develop specs , implement specs. in game, have class army has arraylist of class units:
list<units> unitslist = new arraylist<units>();
i've created class units innerclasses contain different unit types. so, code snippet be:
public class units { int strength, toughness, attacks, save, wounds; class troopunit { public static final int strength = 3; public static final int toughness = 3; public static final int attacks = 1; public static final int save = 5; public int wounds = 1; } class elitetroopunit { public static final int strength = 3; public static final int toughness = 3; public static final int attacks = 1; public static final int save = 4; public int wounds = 1; } }
there more unit types, think can idea. i've tried adding these different innerclasses of units inside units arraylist:
public army(int trooppoints, int elitetrooppoints, int commandpoints, int commandtrooppoints, int fastattackpoints, int heavyattackpoints) { (int = 0; < (trooppoints/troop_cost); i++) if (trooppoints % troop_cost == 0) { if (points < max_points) { unitslist.add(new units.troopunit()); points += troop_cost; numunits++; } } (int = 0; < (elitetrooppoints/elite_troop_cost); i++) if (elitetrooppoints % elite_troop_cost == 0) { if (points < max_points) { unitslist.add(new units.elitetroopunit()); points += elite_troop_cost; numunits++; } } }
however, run issue, because have declare , instantiate arraylist specific type of innerclass in order add inner class it. example, list<units.someunitinnerclass> unitslist = new arraylist<units.someunitinnerclass();
so, there workaround problem can add of innerclasses arraylist? going problem incorrectly? if so, other alternatives? thank you!
edit: had listed "how add different subclasses arraylist, mistake (corrected rudi kershaw).
in example code gave, troopunit
and elitetroopunit
not subtypes of unit
. inner classes.
if want them subclasses of unit
, need extend unit
. example;
public class unit {} public class troopunit extends unit {}
in example above troopunit
extends (and therefore subclass of) unit
. quick glance, looks though add extends unit
end of inner class declarations , should intend.
i hope helps.
references & further reading:
Comments
Post a Comment