73,类的多态性
2015-12-07 15:52
323 查看
#import <Foundation/Foundation.h>
@interface Animal :
NSObject
-(void)eat;
@end
@implementation Animal
-(void)eat{
}
@end
@interface Person :
NSObject
+(void)feed:(Animal *) a;
@end
@implementation Person
+(void)feed:(Animal *)a{
[a eat];
}
@end
@interface Dog : Animal
@end
@implementation Dog
-(void)eat{
NSLog(@"啃骨头!");
}
@end
@interface Cat : Animal
-(void)carryMouse;
@end
@implementation Cat
-(void)eat{
NSLog(@"吃鱼!");
}
-(void)carryMouse{
NSLog(@"抓老鼠!");
}
@end
/*
多态:就是某一个事物的多种形态
程序中的多态:父类指针指向子类对象
优点:提高了代码的扩展性
*/
int main(int argc,const
char * argv[]) {
@autoreleasepool {
//如果父类指针指向子类对象,需要调用子类特有的方法,必须强制转换为子类才能调用
Animal *a = [Catnew];
Cat *c = (Cat *)a;
[c carryMouse];
/*
动态绑定:
1,动态类型能使程序直到执行时,确定对象的真实类型,调用真实类型的方法
*/
Animal *a1 = [Dognew];
[Person feed:a];
[Person feed:a1];
}
return 0;
}
//2015-12-07 15:49:22.609 5,多态[1622:166483]抓老鼠!
//2015-12-07 15:49:22.610 5,多态[1622:166483]吃鱼!
//2015-12-07 15:49:22.610 5,多态[1622:166483]啃骨头!
//Program ended with exit code: 0
@interface Animal :
NSObject
-(void)eat;
@end
@implementation Animal
-(void)eat{
}
@end
@interface Person :
NSObject
+(void)feed:(Animal *) a;
@end
@implementation Person
+(void)feed:(Animal *)a{
[a eat];
}
@end
@interface Dog : Animal
@end
@implementation Dog
-(void)eat{
NSLog(@"啃骨头!");
}
@end
@interface Cat : Animal
-(void)carryMouse;
@end
@implementation Cat
-(void)eat{
NSLog(@"吃鱼!");
}
-(void)carryMouse{
NSLog(@"抓老鼠!");
}
@end
/*
多态:就是某一个事物的多种形态
程序中的多态:父类指针指向子类对象
优点:提高了代码的扩展性
*/
int main(int argc,const
char * argv[]) {
@autoreleasepool {
//如果父类指针指向子类对象,需要调用子类特有的方法,必须强制转换为子类才能调用
Animal *a = [Catnew];
Cat *c = (Cat *)a;
[c carryMouse];
/*
动态绑定:
1,动态类型能使程序直到执行时,确定对象的真实类型,调用真实类型的方法
*/
Animal *a1 = [Dognew];
[Person feed:a];
[Person feed:a1];
}
return 0;
}
//2015-12-07 15:49:22.609 5,多态[1622:166483]抓老鼠!
//2015-12-07 15:49:22.610 5,多态[1622:166483]吃鱼!
//2015-12-07 15:49:22.610 5,多态[1622:166483]啃骨头!
//Program ended with exit code: 0
相关文章推荐
- 网址
- Mysql 多行插入数据
- 解决redmine写操作很慢的问题
- 罗伯特议事规则
- 状态模式的另一种写法
- 实验三的迷宫问题
- 010 MATLAB奇淫技巧之实现图片扫描
- ADO Recordset AddNew一直抛异常
- Remove Duplicates from Sorted List
- 利用Java实现文件中的关键字查询
- Eclipse中使用SVN
- 全自动安装mongoDB数据库的shell脚本
- Html判断客户端使用的Android还是Ios
- wxPython之Boa IDE入门教程
- 大型网站技术架构Tips
- 1055. The World's Richest (25)【排序】——PAT (Advanced Level) Practise
- struts2+jquery.ajax+json实现用户登陆,报错org.apache.struts2.json.JSONException:解决办法
- 使用Preference保存设置
- ssh文件传输命令:sz与rz命令
- Android调用JNI的进阶实例(摄像头预览数据转码RGB播放)