Search code examples
javaoopenumsencapsulation

How do I encapsulate enums in Java


I'm trying to create a StandardCard class which uses enums for suits and numbers. I have the code as it is currently below.

My problem is that the enums should be accessible to the Driver class which is adding cards to the deck. Having read about design patterns recently I feel that I should have a StandardCardEnums class and create an object of this class within the StandardCard class to add modularity. Is this the way to go? It feels clunky as I then need to do something like

StandardCardEnum myEnums = new StandardCardEnum;
private StandardCardEnum.Suit suit;
etc.....

My current code is below, the issues I see with it are 1) The enums are hard-coded within the card class, duplication is definitely going to happen 2) The Driver class needs to know about the enums to populate cards in the deck hence violating object encapsulation.

Can anyone with more experience point me towards a good standard to start applying to these types of situations? I'm trying to move away from programming towards software development. I'm hoping to be able to create a modular card-game framework that will allow me to add in different card games and even deck compositions and card types with a minimum of effort.

public class StandardCard extends Card
{
public enum Suit {CLUBS, DIAMONDS, HEARTS , SPADES };
public enum Number {ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};

private Suit suit;
private Number number;

public StandardCard(StandardCard.Suit suit, StandardCard.Number number)
{
    this.suit = suit;
    this.number = number;
}

public StandardCard()
{
}

public Suit getSuit()
{
    return suit;
}

public Number getNumber()
{
    return number;
}

public void setSuit(Suit s)
{
    this.suit = s;
}

public void setNumber(Number n)
{
    this.number = n;
}
}

Solution

  • You should rather make your enums static:

    public static enum Suit {CLUBS, DIAMONDS, HEARTS , SPADES };
    public static enum Number {ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};
    

    This way you can access them as StandardCard.Suit.CLUBS from anywhere in your code (e.g. from Driver), but they're still encapsulated into StandardCard - they have no meaning outside this world.