您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: