黑马程序员——OC三大特性-7:多态

来源:互联网 发布:哪款vpn软件好 编辑:程序博客网 时间:2024/05/18 02:17

————————java培训、Andoroid培训、IOS培训、.Net培训、期待与您交流!————————

多态

代码的体现:父类指针指向子类对象

多态的局限性:父类类型的变量不能调用子类的方法,必须强专转为子类对象

没有继承就没有多态

好处:函数\方法参数中使用的是父类类型,可以传入子类、父类对象

//动物#import <Foundation/Foundation.h>@interface Animal : NSObject- (void)eat;@end@implementation Animal- (void)eat{    NSLog(@"Animal-吃东西");}@end//狗@interface Dog : Animal- (void)eat;@end@implementation Dog- (void)eat{    NSLog(@"Dog-吃东西");}@end//猫@interface Cat : Animal- (void)eat;@end@implementation Cat- (void)eat{    NSLog(@"Cat-吃东西");}@endvoid feed(Animal *a){    [a eat];}int main(){    Animal *a=[Dog new];    Dog *aa=(Dog *)a;    [a eat];        Animal *cc=[Cat new];    feed(cc);    return 1;}



0 0