为什么我的超类对象调用它的子类方法?

时间:2013-08-22 09:26:15

标签: objective-c stanford-nlp

我在这里看到了很多有用的帖子,但这是我第一次发帖!

我正在研究臭名昭着的斯坦福开放课程项目:Matchismo。虽然我得到了一切正常,但我不明白示例代码的一部分。

基本上,下面的代码用于获取Card对象以与另一张卡进行比较。

- (void) flipCardAtIndex: (NSUInteger)index
{
    Card *card = [self cardAtIndex:index];
    if (card && !card.isUnplayable)
    {
        if (!card.isFaceUp)
        {
            for (Card* otherCard in self.cards)//for-in loop
            {
                if (otherCard.isFaceUp && !otherCard.isUnplayable)
                {
                    int matchScore = [card match:@[otherCard]];
......

这就是cardAtIndex的工作原理:

-(Card *) cardAtIndex:(NSUInteger)index
{
    if (index < [self.cards count])
        //dot notation is used for property
        //[] is used for method
    {
        return self.cards[index];
    }
    return nil;
}

以下是Match(card *)和Match(playingCard)

的方法

匹配(卡*)

-(int) match:(NSArray *)otherCards
{
    NSLog(@"here");
    int score = 0;

    for (Card *card in otherCards)
    {
        if ([card.content isEqualToString:self.content])
            score = 1;
        {
            NSLog(@"Card Match");
        }

    }
    return score;
}

匹配(游戏牌*)

-(int) match: (NSArray *)otherCards;
{
    int score = 0;
    if ([otherCards count] == 1)
    {
        PlayingCard *otherCard = [otherCards lastObject];//the last object in the array
        if ([otherCard.suit isEqualToString:self.suit])
            score = 1;
        else if (otherCard.rank == self.rank)
            score = 4;
        NSLog(@"PlayingCard Match");
    }
    return score; 
}

它工作正常,但我不明白为什么当Card *对象调用方法时,会调用其子类的PlayingCard方法。 非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

这个概念叫做Polymorphism

它允许您拥有一个提供某种接口的基类,以及一组以不同方式实现这些方法的子类。经典示例是Drawable类方法draw及其子类CircleRectangle,它们都覆盖draw方法以某种特定方式呈现自己

对于你的Card基类,它调用自己的接口方法match,但作为对象实际上不是Card的实例,而是PlayingCard的实例调用子类,子类方法来提供特定的实现。

答案 1 :(得分:0)

在视图控制器.m文件中,属性“deck”必须初始化为类PlayingCardDeck,而在PlayingCardDeck.m中,卡类是PalyingCard。所以即使你把你的卡声明为类卡,它所调用的方法仍然是PlayCard类中的那个。

相关问题