黑马程序员--多态

------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方法




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值