OC学习笔记 面向对象 多态

 1 #import <Foundation/Foundation.h>
 2 @interface Animal : NSObject
 3 - (void) eat;
 4 @end
 5 @implementation Animal
 6 - (void) eat
 7 {
 8     NSLog(@"用嘴巴吃啊");
 9 }
10 //如果参数中是父类类型可以传入父类和子类对象。
11 void feed (Animal *animal)
12 {
13     [animal eat];
14 }
15 @end
16 
17 @interface Dog : Animal
18 - (void) eat;
19 @end
20 @implementation Dog
21 - (void) eat
22 {
23     NSLog(@"狗仔用嘴巴吃啊");
24     [super eat];
25 }
26 @end
27 
28 @interface Cat :  Animal
29 @end
30 @implementation Cat
31 @end
32 
33 int main()
34 {   //代码体现多态就是父类类型指针指向子类对象  没有继承就没有多态
35     //多态 局限性 父类类型变量不能直接调用子类对象 需要强制转换
36     Animal *animal = [Dog new];
37     feed(animal);
38     Cat *c = [Cat new];
39     feed(c);
40     Dog *d = (Dog *)animal;//强制转换类型
41     [d eat];
42     return 0;
43 }

 多态总结

多态在代码中的体现,即为多种形态,必须要有继承,没有继承就没有多态。

在使用多态是,会进行动态检测,以调用真实的对象方法。

多态在代码中的体现即父类指针指向子类对象。

//多态 父类指针指向子类对象 字符串继承NSObject
NSObject *obj1 = [[NSObject alloc]init];
obj1 = @"hello";//字符串赋值给父类对象

原文地址:https://www.cnblogs.com/zhangdashao/p/4443410.html