简体   繁体   中英

How would I store different types of an object?

I am creating a card game in Java. Each card object can have a different suit out of a selection of four and each suit alters the way the card object functions with other objects in the game . Otherwise, the cards behave the same way. I can assign each card object a suit by using a Boolean variable for each suit, but doing that feels like a messy solution where things might go wrong.

Would using an Enum be a better solution?

Your best bet would be to make an Abstract base class that has an abstract method that each suit inherits from and implements.

abstract class AbstractSuit {

  public abstract int modify();
}

Then each suit would extend AbstractSuit

class Hearts extends AbstractSuit {

  @Override
  public int modify() {
    return 1 + 1;
  }
}

class Spades extends AbstractSuit {

  @Override
  public int modify() {
    return 2 + 2;
  }
}

Then you can store each of your object as AbstractSuits in what ever collection you want and can call modify()

List<AbstractSuit> suitList = new ArrayList<>();
suitList.add(new Hearts());
suitList.add(new Spades());

for(AbstractSuit suit : suitList) {
  System.out.println(suit.modify());
}

Output would be

2
4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM