Search code examples
objective-cmethodssubclasssuperclassderived-class

Why can I call a subclass method with a superclass pointer in Objective-C?


I have two classes, Food and Nacho. Food is Nacho's super class.

Food *junk = [[Nacho alloc] init];

is valid as long as I call Food's methods, right?

But how come that Food pointer can call one of Nacho's methods (which is defined as an additional method in the subclass)?

  • fixed , removed 'NS' prefix from class name.

Solution

  • Well, it isn't really an NSMom instance, so you can call it at runtime because the NSSon instance does implement the method. At compile time you do need to do something to tell the compiler that it shouldn't check the type (or that it should trust you).

    Aside - don't prefix your own classes with 'NS' in real code. Sooner or later you'll get a clash with an Apple class.