main:
1 #import <Foundation/Foundation.h> 2 #import "Animal.h" 3 #import "Fish.h" 4 #import "Bird.h" 5 6 void doAction(Animal *ani) 7 { 8 [ani action]; //用父类参数ani,调用父类中的action 9 } 10 11 int main(int argc, const char * argv[]) { 12 @autoreleasepool { 13 Animal *animal=[[Animal alloc]init]; 14 Bird *bird=[[Bird alloc]init]; 15 Fish *fish=[[Fish alloc]init]; 16 17 doAction(animal); //传入父类实例animal 18 doAction(bird); //传入子类实例bird 19 doAction(fish); //传入子类实例fish 20 } 21 return 0; 22 }
Animal.h:
1 #import <Foundation/Foundation.h> 2 3 @interface Animal : NSObject 4 -(void)action; 5 @end
Animal.m:
1 #import "Animal.h" 2 3 @implementation Animal 4 -(void)action{ 5 NSLog(@"Animal Moving~"); 6 } 7 @end
Fish.h:
1 #import "Animal.h" 2 3 @interface Fish : Animal 4 -(void)action; 5 @end
Fish.m:
1 #import "Fish.h" 2 3 @implementation Fish 4 -(void)action{ 5 NSLog(@"Fish Swiming~"); 6 } 7 @end
Bird.h:
#import "Animal.h" @interface Bird : Animal -(void)action; @end
Bird.m:
1 #import "Bird.h" 2 3 @implementation Bird 4 -(void)action{ 5 NSLog(@"Bird Flying~"); 6 } 7 @end
原文:http://www.cnblogs.com/wangyang1987/p/5107376.html