So, I'm building a very basic program based on the Warhammer 40k tabletop game as an extra credit assignment for my Comp Sci class. I get to develop the specs and then I implement the specs. In this game, I have a class Army that has an ArrayList of class Units:
List<Units> unitsList = new ArrayList<Units>();
I've created the class Units with innerclasses that contain the different unit types. So, a code snippet from that would 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 are more unit types, but I think you can get the idea. I've tried adding these different innerclasses of Units inside the Units ArrayList:
public Army(int troopPoints, int eliteTroopPoints, int commandPoints,
int commandTroopPoints, int fastAttackPoints, int heavyAttackPoints)
{
for (int i = 0; i < (troopPoints/TROOP_COST); i++)
if (troopPoints % TROOP_COST == 0)
{
if (points < MAX_POINTS)
{
unitsList.add(new Units.TroopUnit());
points += TROOP_COST;
numUnits++;
}
}
for (int i = 0; i < (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, I run into an issue, because I have to declare and instantiate the ArrayList with a specific type of innerclass in order to add an inner class to it. For example,
List<Units.someUnitInnerClass> unitsList = new ArrayList<Units.someUnitInnerClass();
So, is there a workaround for this problem where I can add any of the innerclasses to the ArrayList? Am I going about this problem incorrectly? If so, what are other alternatives? Thank you!
EDIT: I originally had listed this as "How do I add different subclasses to an ArrayList, but that was a mistake (corrected by Rudi Kershaw).
In the example code you gave,
TroopUnit
andEliteTroopUnit
are not subtypes ofUnit
. They are inner classes.If you want them to be subclasses of
Unit
, they need to extendUnit
. For example;In the example above
TroopUnit
extends (and is therefore a subclass of)Unit
. From a quick glance, it looks as though you could just addextends Unit
to the end of your inner class declarations and it should do as you intend.I hope this helps.
References & Further Reading: