[英]Can not access method of subclass
I am working on a party game in java.我正在 java 中开发派对游戏。
I struggle to make a proper class hierarchy for cards.我努力为卡片制作正确的 class 层次结构。 The player can carry cards.玩家可以携带卡片。 There are different kind of cards so I made for each card group a separate class.有不同种类的卡,所以我为每个卡组制作了一个单独的 class。 There are the following classes for cards:卡片有以下类别:
First I construct a NumberedSpecialCard:首先我构造了一个 NumberedSpecialCard:
NumberedSpecialCard firstPlayerThirdCard = new NumberedSpecialCard(13);
Next I add the card to a list (here firstPlayerCards)接下来我将卡片添加到列表中(这里是 firstPlayerCards)
List<Card> firstPlayerCards = new LinkedList<Card>();
firstPlayerCards.add(firstPlayerThirdCard);
Now I create a player object.现在我创建一个播放器 object。 The player can carry a list of cards.玩家可以携带一张卡片列表。
Player firstPlayer = new Player(firstPlayerMumbles, firstPlayerCards, 1,"Player ONE");
The problem is that i can not access the 'bringMumbleIntoPlay' method which is defined in the NumberedSpecialCard class.问题是我无法访问 NumberedSpecialCard class 中定义的“bringMumbleIntoPlay”方法。
The following does not work:以下不起作用:
firstPlayer.getCards().get(2).bringMumbleIntoPlay(allPlayers, firstPlayer, 1);
I do not want to change the class hierarchy (It pictures the real conditions very well.).我不想更改 class 层次结构(它很好地描绘了真实情况。)。 Can someone help me?有人能帮我吗?
firstPlayer.getCards()
is a list of Card
s. firstPlayer.getCards()
是Card
的列表。 Now a Card
does not have the method bringMumbleIntoPlay
in it.现在Card
中没有方法bringMumbleIntoPlay
。 So compiler has no idea which subclass it needs to look into .所以编译器不知道它需要查看哪个子类。 That's why it complains.这就是它抱怨的原因。
One alternative is to use explicit casting with a safety check using instanceof一种替代方法是使用显式转换和使用instanceof的安全检查
Card c = firstPlayer.getCards().get(2);
if(c instanceof NumberedSpecialCard){
NumberedSpecialCard nsc = (NumberedSpecialCard)c;
nsc.bringMumbleIntoPlay(allPlayers, firstPlayer, 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.