ios开发之-继承的实现运用

来源:互联网 发布:指定变号发短信软件 编辑:程序博客网 时间:2024/06/05 05:40
////  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



0 0
原创粉丝点击