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
- Objective-c 多态
- Objective-C多态
- Objective-C多态(二)
- Objective-C 多态
- Objective-C 多态
- Objective C多态
- Objective-C----多态
- Objective-C 【多态】
- Objective-C: 多态
- Objective-C多态
- Objective-c-多态
- 学习笔记(objective-c)-多态
- Objective-C
- Objective-C
- Objective-C
- Objective-c
- Objective-c
- Objective-C
- JavaScript Date、Number 格式化总结
- webservices使用MTOM附件抛出的内存溢出
- Java---IO(Scanner和BufferedReader)
- 1021 个位数统计
- mongoDB基础知识2----基本操作(CRUD),索引(常见、全文、地理位置)
- Objective-C: 多态
- 二维数组顺时针输出
- 实现strtok_r()函数
- ActiveMQ与Spring整合:(1)基本使用
- jsp中四个域对象
- Struts2 中Action的执行结果类型
- 关于H264的补充
- 关于Can't create handler inside thread that has not called Looper.prepare()
- Android 蓝牙开发基本流程