Ios Development Zoo management inheritance polymorphism implementation, ios Polymorphism
//// Main. m // inherit //// # import <Foundation/Foundation. h> # import "Animal. h "# import" Cat. h "# import" Dog. h "# import" FeedMan. h "int main (int argc, const char * argv []) {// Animal * animal = [Animal new]; // [animal eat]; //// [animal sleep]; /// forgot to introduce the header file // Animal * cat = [[Cat alloc] init]; // [cat eat]; // Cat * cat = [[Cat alloc] init]; // [cat catchMouse]; // Dog * dog = [[Dog alloc] init]; /// [do G bark]; // The parent class pointer to save the subclass object. How can I call the subclass object method? // Animal * animal_cat = [[Cat alloc] init]; // FeedMan * man = [[FeedMan alloc] init]; // [man showName: animal_cat]; // [animal_cat eat]; // [animal_cat setName: @ "Hello Cat"]; Animal * animal_dog = [[Dog alloc] init]; feedMan * man = [[FeedMan alloc] init]; [man showName: animal_dog]; [man FeedAnimal: animal_dog]; // The subclass calls the method of the parent class, how to implement different methods? Return 0 ;}
//// FeedMan. h // inherit // # import "Animal. h "@ interface FeedMan: NSObject-(void) showName :( Animal *) animal;-(void) FeedAnimal :( Animal *) animal; @ end
//// FeedMan. m // inherit # import "FeedMan. h "# import" Dog. h "# import" Cat. h "@ implementation FeedMan-(void) FeedAnimal :( Animal *) animal {if ([animal isKindOfClass: [Dog class]) {Dog * dog = (Dog *) animal; [dog eat] ;}}- (void) showName :( Animal *) animal {// can dynamically detect a class used by Animal types? If ([animal isKindOfClass: [Dog class]) {// forced type conversion required Dog * dog = (Dog *) animal; [dog bark];} else if ([animal isKindOfClass: [Cat class]) {Cat * cat = (Cat *) animal; [cat catchMouse] ;}}@ end
//// Animal. h // inherit # import <Foundation/Foundation. h> @ interface Animal: NSObject {NSString * _ name; int _ age;} @ property NSString * name; @ property int age;-(void) eat;-(void) sleep;-(void) showAge; @ end
//// Animal. m // inherit // # import "Animal. h "@ implementation Animal-(void) eat {NSLog (@" Animal eating ");}-(void) sleep {NSLog (@" Animal sleeping ");} -(void) showAge {NSLog (@ "age of a small animal");} @ end
/// Dog. h // inherit // # import "Animal. h" @ interface Dog: Animal {}-(void) bark;-(void) eat; @ end
// Dog. m // inherit // # import "Dog. h "@ implementation Dog-(void) bark {NSLog (@" ");}-(void) eat {NSLog (@" ");} @ end
/// Cat. h // inherit # import "Animal. h" @ interface Cat: Animal {}-(void) catchMouse;-(void) eat; @ end
// Cat. m // inherit // # import "Cat. h" @ implementation Cat {}-(void) catchMouse {NSLog (@ "the Cat will catch a mouse! ");}-(Void) eat {NSLog (@" kitten eats fish ");} @ end
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.