[Objective-c 基础 - 2.4] 多态

时间:2023-03-09 18:37:51
[Objective-c 基础 - 2.4] 多态

A.对象的多种形态

1.父类指针指向子类对象
2.调用方法的时候,会动态监测真实地对象的方法
3.没有继承,就没有多态
4.好处:用一个父类指针可以指向不同的子类对象
5.强制转换类型之后就能使用子类特有的方法,否则会出现warning(仍可以正常运行,即不论指针类型,只要对象存在实际方法就可以运行)
 #import <Foundation/Foundation.h>

 @interface Animal : NSObject
- (void) eat;
@end @interface Dog : Animal
- (void) run;
@end @interface Cat : Animal @end @implementation Animal
- (void) eat
{
NSLog(@"吃东西---");
} @end @implementation Dog
- (void) eat
{
NSLog(@"狗狗吃东西");
} - (void) run
{
NSLog(@"狗狗跑起来了");
}
@end @implementation Cat - (void) eat
{
NSLog(@"猫猫吃东西");
} @end void feed(Animal *animal)
{
NSLog(@"开始喂动物");
[animal eat];
} int main()
{
Animal *a = [Dog new];
[a eat];
Animal *c = [Cat new];
[c eat]; feed(a);
feed(c); Dog *dog = (Dog *)a;
[dog run]; return ;
}