------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
1.什么是多态:
不同的对象以自己的方式相应相同名称方法的能力称为多态。
2.多态的条件:
有继承关系、有方法重写、父类的声明变量指向子类对象。
用父类类型的指针指向了子类对象,这就是多态。
Dog *d = [Dog new];
Animal *ani = [Dog new];
3.多态的好处:
简化了编程接口,它容许在类和类之间重用一些习惯的命名,而不用为每一个新加的函数命名一个新名字。这样,编程接口就是一些抽象的行为的集合,从而和实现接口的类的区分开来。
4.代码实现
假设我们已经定义了 Animal Dog Cat BigYellowDog 四个类,Dog和Cat继承Animal类,BigYellowDog继承Dog类
int main(int argc, const char * argv[]) {
@autoreleasepool {
Animal *ani = [Animal new];
[ani run];
Dog *d1 = [Dog new];
[d1 run];
Cat *cat = [Cat new];
[cat run];
Animal *a2 = [Dog new];
//父类指针指向了子类对象
[a2 run];
Animal *a3 = [Cat new];
[a3 run];
Dog *d4 = [BigYellowDog new];
[d4 run];
Animal *a5 = [BigYellowDog new];
[a5 run];
}
return 0;
}
Animal不仅可以调用Dog和Cat的run方法,同时可以调用BigYellowDog方法,因为 BigYellowDog父类的父类是Animal
5.多态的使用注意:
Animal *a6 = [Dog new];
//a6 Animal类型,编译的时候会在Animal.h中查找声明,没有找到eat方法,所以报错
//[a6 eat]; 变异的时候报错
[(Dog *)a6 eat];
//把a6强制转换为Dog类型
//下面的用法是错误的
Animal *a7 = [Animal new];
//[a7 eat]; 不可以,错误的用法
[(Dog *)a7 eat];
//虽然编译器没有报错,但是实际上运行的时候a7对象还是Animal对象,不是Dog对象,Animal类中没有eat方法