1 /*====================Animallei====================*/ 2 //1.创建抽象类 Animal 3 @interface Animal : NSObject 4 { 5 NSString *_eat; 6 } 7 //2.把子类都需要实现的方法抽取出来,创建eat方法,然后在.m文件实现该方法 8 -(void)eat; 9 10 @end 11 12 @implementation Animal 13 //3.方法实现,可以只实现不写过程,因为在子类.m文件中会重写该方法 14 -(void)eat{ 15 // NSLog(@"Animal eating"); 16 } 17 18 @end 19 20 21 /*=======================Tiger===================*/ 22 //创建Tiger类继承Animal父类,子类继承了父类所有的变量和方法 23 //不用在.h文件重新声明eat方法,直接在.m文件@implementation实现重写eat方法 24 //因为子类已经继承父类方法 25 26 @implementation Tiger 27 //4.重写抽象类父类Animal的eat方法 28 -(void)eat{ 29 NSLog(@"Tiger eating"); 30 } 31 32 @end 33 34 35 /*=================Elephant================*/ 36 //创建Elephant类继承Animal父类 37 //不用在.h文件重新声明eat方法,直接在.m文件@implementation实现重写eat方法 38 //因为子类已经继承父类方法 39 40 @implementation Elephant 41 //4.重写抽象类父类Animal的eat方法 42 -(void)eat{ 43 NSLog(@"Elephant eating"); 44 } 45 46 @end 47 48 49 50 /*==================Administrator================*/ 51 //创建管理员类 52 #import "Animal.h" 53 @interface Administrator : NSObject 54 55 //5.导入Animal头文件,使用Animal指针调用eat方法; 56 -(void)feedAdimal:(Animal *)feeding; 57 58 @end 59 60 @implementation Administrator 61 62 -(void)feedAdimal:(Animal *)feeding{ 63 64 [feeding eat]; 65 66 } 67 68 @end 69 70 71 72 /*======================================*/ 73 Administrator *admin = [[Administrator alloc]init];
//admin feedAdimal:(Animal *)父类通过子类指针调用子类方法 74 75 //老虎 76 Tiger *tiger = [[Tiger alloc]init]; 77 [admin feedAdimal:tiger]; 78 //打印结果Tiger eat; 79 80 //大象 81 Elephant *elephant = [[Elephant alloc]init]; 82 [admin feedAdimal:elephant]; 83 //打印结果Elephant eat;
浙公网安备 33010602011771号