多态就是一个父类在声明的时候不确定自己指向哪个子类对象,只有在程序运行时才能确定自己指向哪个子类对象,从而使用一个父类有可以展现出多种子类的形态。
比如:
#import <Foundation/Foundation.h>
/**********父类************/
@interface Animal : NSObject
{
int _age;
double _weight;
}
- (void)setAge:(int)age;
- (int)age;
- (void)setWeight:(double)weight;
- (double)weight;
@end
@implementation Animal
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
- (void)setWeight:(double)weight
{
_weight = weight;
}
-(double)weight
{
return _weight;
}
@end
/**********子类1************/
@interface Dog: Animal
- (void)eat();
@end
@implementation Dog
- (void)eat()
{
NSLog("Dog eat");
}
@end
/**********子类2************/
@interface Cat: Animal
- (void)eat();
@end
@implementation Cat
- (void)eat()
{
NSLog("Cat eat");
}
@end
int main()
{
//调用子类Dog的eat方法
Animal *a = [[Dog alloc] init];
[a eat];
//调用子类Cat的eat方法
Animal *a = [[Cat alloc] init];
[a eat];
return 0;
}
使用注意:
1. 如果一个函数的参数是父类类型,则可以传入父类、子类对象。
2. 不得使用子类类型创建父类对象。