0

deck is my superclass and playingCardDeck is my subclass of deck. i found that i can i instantiation my superclass by using my subclass which confuse me a lot. Can you tell me about this.Which init method will be used and any other features about this.thanks in advance.

#import "XYZViewController.h"
#import "PlayingCardDeck.h"
@interface XYZViewController ()
@property (weak, nonatomic) IBOutlet UILabel *flipLabel;
@property (nonatomic) NSUInteger flipCount;
@property (nonatomic) Deck *deck;
@end

@implementation XYZViewController
- (Deck *)deck
{
    if (!_deck) {
        _deck=[self createDeck];
    }
    return _deck;
}
- (Deck *)createDeck
{
    return [[PlayingCardDeck alloc]init];
}
cozybed
  • 3
  • 3

1 Answers1

1

This shouldn't be surprising at all. This is quite normal OOP (it's formally called the Liskov substitution principle). An object of type Animal can accept an object of type Dog. But you can only call Animal methods on it.

In your example, the init for PlayingCardDeck will be executed. Anyone who accesses deck will only be able to call methods that are defined on Deck, but the implementation will be the one provided by PlayingCardDeck.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • what about the instance variables that the subclass hold? Can `deck` have access to them? Thanks a lot.By the way, can you recommend me a book on oc which talks about the these kind of thing(class subclass,inherit) in details.I'm new to the oc(even new to the OOP language).thanks a lot.Really thanks:) – cozybed Aug 01 '14 at 16:30
  • This isn't really Objective-C; this is just object oriented programming (OOP). The instance will of have all of its properties. But any caller who has a `Deck`-typed variable won't be able to access anything that isn't part of `Deck`. There are a many good introductions to OOP (most of the ideas are equivalent across OOP languages). http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep http://docs.oracle.com/javase/tutorial/java/concepts/ (or just search for "introduction to oop") – Rob Napier Aug 01 '14 at 18:26