So, I've been working on some playing cards in Java. (Not for any practical purpose really, I just enjoy playing cards and they're good practice) Now, right now, I'm making some Card Structures, decks, hands, piles, etc. They're all essentially the same, so I figure that I'd like to use some inheritance.
The problem that I've encountered is that the core of each structure is some type of collection, but they don't all use the same collection type. A deck uses a Stack, since a deck essentially functions as a stack most often. But, a hand uses an ArrayList (If there is something more efficient than an ArrayList to use, that would be good to know as well). So, when trying to write an abstract class, I'd like to avoid using abstract methods (as it defeats the original purpose of making an abstract class, to conserve code). But, all of these methods rely on the core collection, for obvious reasons, but I don't know what type the collection is. This is what I've tried so far:
public abstract class CardSet
{
protected AbstractCollection<Card> elCollection;
public CardSet()
{
super();
}
public CardSet(Card[] cards)
{
super();
for(Card c: cards)
elCollection.add(c);
}
public void add(Card c)
{
elCollection.add(c);
}
}
public class Pair extends CardSet //Pair is just a dummy class to get inheritance right
{
ArrayList<Card> elPair;
public Pair()
{
elPair = new ArrayList<Card>(); //elPair is defined, because casting
elCollection = elPair; // elCollection to arraylist would be a pain.
}
public Pair(Card[] cards)
{ this();
super(cards);
}
}
First off, forgive my variable names. I used to name everything "theVariable", but I decided that using "el" was more interesting. (You've got to amuse yourself somehow, right?) Also, using protected was just for the sake of simplicity.
Now, the general idea seems to work, defining a variable in the abstract class, and then defining an alias of it in the child class, but I'm not so sure that it's a great practice. The real problem I'm having is with the constructor. The constructor in Pair that accepts an array of Cards doesn't work, because to add the cards, I would first need to create the collection (in this case, the ArrayList) before the parent constructor tries to add the cards. Is there any way to work around this? Is this even a viable way of handling inheritance?