So in Objective-C, I have a PlayingCardDeck class (which contains an array of PlayingCards, which is a subclass of Cards) that has a drawRandom method (inherited from the Deck class) which returns a randomly Card object from that array.
I have the result of this drawRandom method assigned to Card *hello, since a card object is returned, so I can't assign the result to a PlayingCard *hello.
If I were to want to access some methods that I implemented in PlayingCards, how would I do so? I was forced to assign to Card, so I can't access any of the PlayingCard methods.
Should I reimplement the drawRandom method in PlayingCardDeck so that it returns a PlayingCard instead?
Or is there some other way to do this? (since it seems to be a waste to have to reimplement all of my superclass methods...if I do that, what's the point of subclassing?)
Am I simply missing something?
It looks like a bit of a flaw in the object model, so perhaps you should return PlayingCards
, but if you need to do this, the safe way is to check the Class of the object, and then cast it and make the method calls.
if ([card isKindOfClass: [PlayingCard class]]) {
[(PlayingCard*)card doMyPlayingCardMethod];
}
This safely checks that the card
object is a PlayingCard
or a derivative, and then calls the -doMyPlayingCardMethod
method on it.
As far as the "what's the point of subclassing?" question, it's really more for the other case. So, for example, if you had FacePlayingCard
and NumberPlayingCard
that were all subclasses of PlayingCard
, you could have a -drawCard
method that knew how to draw the face cards differently than the number cards.
In this case, you're abstracting Card
from PlayingCard
, but there doesn't seem to be anything you want to do with Card
, so it's kind of a meaningless place to put the subclass.
If, on the other hand, you had CollectingCard
which was also a subclass of Card
and you wanted to be able to shuffle them as well, that would make some more sense.