The easiest way is simply to make d
static
(it's also worth making it final
, so that no subclass can replace it with a different instance):
public abstract class Pile {
protected static final Deck d=new Deck();
public abstract void PrintCard();
public abstract boolean IsEmpty();
}
However, static variables like this can be problematic, especially from a testing perspective. It is also tricky to change later if you need some Pile
s to have one Deck
whilst others have a different Deck
(e.g. JonK's example).
You can alternatively inject the Deck
as a parameter:
public abstract class Pile {
protected final Deck d;
public Pile(Deck d) {
this.d = d;
}
public abstract void PrintCard();
public abstract boolean IsEmpty();
}
You can now inject a value of your choosing (e.g. a mock) when you construct the Pile
. The second solution is the one I would choose.