开发者

Way to access variables of class from collection of its super?

Suppose I have:

class Card{ }

class CardUnit extends 开发者_如何学编程Card {
  int attack = 4;
}

ArrayList<Card> listCards;

Is there any way to put both Cards and CardUnits in my listCards array and still be able to access the attack variable of the CardUnits that are in the list? Or must I put the variable in the Card class too?


If all Cards have an attack, you can add an abstract getAttack() to the superclass.

class Card {
  public abstract int getAttack();
}

Otherwise, you could have an interface IAttackCard with a method getAttack(), that CardUnit implements. Then, when accessing cards from the list, you can check whether they're instances of IAttackCard.

   interface ICardAttack {
      public int getAttack();
   }

   class CardUnit extends Card implements ICardAttack {
      private int attack; 
      @Override
      public int getAttack() { return attack; }
    }

Testing directly for CardUnit with instanceof would interfere with the open-closed principle -- adding a new subclass of Card could require modification of existing code that works with Cards.


If you add a method getAttack() in the Card class (with a default value) and override it in CardUnit you can access it.

Maybe you want to make the Card class abstract (you can't create objects); you can make the getAttack() method abstract and force subclasses to implement it.


You could use instanceof to test for CardUnit, then act if true.

for (Card i : list) {
  if (i instanceof CardUnit){
    actOnAttackValue( (CardUnit) i );
  }
}

I'm not a fan of adding an abstract method to Card because

  • You never said it was an abstract class. You may be instantiating it
  • It doesn't make sense in other context. Like adding a gaveBirth() method to a Human class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜