Objective-C: 多态

来源:互联网 发布:安卓手机优化软件 编辑:程序博客网 时间:2024/05/21 16:46

1.多态

1.一个对外接口,多个对内实现
void test1(){    CZAnimal *a=[[CZDog alloc]initWithName:@"额" andAge:3];    [a eat]; //父类的指针调用子类用重写的方法    [a sleep];    // [a watchHome] 父类的指针不能调用子类中派生的方法    a=[[CZCat alloc]initWithName:@"老咪" andAge:3];    [a eat];}int main(int argc, const char * argv[]) {    @autoreleasepool {        test1();    }    return 0;}
2.在OC程序中,体现为父类的指针可以指向子类的对象,从而调用子类中重写的父类的方法3.使用形式    3.1 函数参数多态
void show(CZAnimal *a){    [a eat];}void test2(){    CZDog* dog=[[CZDog alloc]initWithName:@"小黑" andAge:3];    show(dog);    CZCat* cat=[[CZCat alloc]initWithName:@"老咪" andAge:4];    show(cat);}
    3.2 数组多态.
void test3(){    CZAnimal* a[3];    a[0]=[[CZAnimal alloc]initWithName:@"无名" andAge:0];    a[1]=[[CZDog alloc]initWithName:@"小黑子" andAge:3];    a[2]=[[CZCat alloc]initWithName:@"老咪" andAge:2];    for(int i=0;i<3;i++)    {        [a[i] eat];    }}
    3.3 返回值多态
typedef enum{    ANIMAL,    DOG,    CAT}Type;CZAnimal* get(Type type){    switch (type) {        case ANIMAL:            return [[CZAnimal alloc]initWithName:@"无名" andAge:0];            break;        case DOG:            return [[CZDog alloc]initWithName:@"小黑子" andAge:3];            break;        case CAT:            return [[CZCat alloc ]initWithName:@"老咪" andAge:2];        default:            break;    }}void test4(){    [get(DOG) eat];    [get(CAT) eat];}

动物管理员

#import <Foundation/Foundation.h>#import "CZFeeder.h"#import "CZMeat.h"#import "CZTiger.h"#import "CZSheep.h"#import "CZGrass.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        CZFeeder* feeder=[[CZFeeder alloc]init];        CZTiger* tiger=[[CZTiger alloc]initWithName:@"跳跳虎"];        CZMeat* meat=[[CZMeat alloc]initWithName:@"羊肉"];        [feeder feedForAnimal:tiger withFood:meat];        CZSheep* sheep=[[CZSheep alloc]initWithName:@"咩咩羊"];        CZGrass* grass=[[CZGrass alloc]initWithName:@"马达加斯加香草"];        [feeder feedForAnimal:sheep withFood:grass];       }    return 0;}
0 0
原创粉丝点击