標籤:多態 繼承 ios開發 動物園管理系統 foundation架構
//// main.m// 繼承////#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]; // //忘記引入標頭檔// Animal * cat =[[Cat alloc]init];// // [cat eat]; // Cat * cat = [[Cat alloc]init];// // [cat catchMouse];// // Dog * dog = [[Dog alloc]init];// // [dog bark];// //父類指標儲存子類對象,怎樣調用子類對象的方法? // 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]; //子類調用父類的方法,怎樣實現方法的不同性? return 0;}
//// FeedMan.h// 繼承//#import "Animal.h"@interface FeedMan : NSObject-(void)showName:(Animal *)animal;-(void)FeedAnimal:(Animal *)animal;@end
//// FeedMan.m// 繼承#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{ //可以動態檢測動物的類型用到的一個類? if([animal isKindOfClass:[Dog class]]) { //需要強制類型轉換 Dog * dog = (Dog *)animal; [dog bark]; } else if ([animal isKindOfClass:[Cat class]]) { Cat * cat = (Cat *)animal; [cat catchMouse]; } }@end
//// Animal.h// 繼承#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// 繼承//#import "Animal.h"@implementation Animal-(void)eat{ NSLog(@"動物吃東西");}-(void)sleep{ NSLog(@"動物睡覺了");}-(void)showAge{ NSLog(@"小動物的年齡");}@end
//// Dog.h// 繼承//#import "Animal.h"@interface Dog : Animal{ }-(void)bark;-(void)eat;@end
// Dog.m// 繼承//#import "Dog.h"@implementation Dog-(void)bark{ NSLog(@"小狗汪汪叫");}-(void)eat{ NSLog(@"小狗吃東西");}@end
//// Cat.h// 繼承#import "Animal.h"@interface Cat : Animal{ }-(void)catchMouse;-(void)eat;@end
// Cat.m// 繼承//#import "Cat.h"@implementation Cat{ }-(void)catchMouse{ NSLog(@"貓咪會捉老鼠!");}-(void)eat{ NSLog(@"小貓吃小魚");}@end
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
ios開發動物園管理 繼承多態的實現