zoukankan      html  css  js  c++  java
  • 10-使用多态的好处和局限性

    使用多态的好处

         如果函数方法的参数是父类类型,那么父类、子类对象都可以传入。

     1 #import <Foundation/Foundation.h>
     2 //Animal类
     3 @interface Animal : NSObject
     4 - (void)eat;
     5 @end
     6 @implementation Animal
     7 - (void)eat
     8 {
     9     NSLog(@"Animal---吃东西");
    10 }
    11 @end
    12 
    13 //Dog类
    14 @interface Dog : Animal
    15 - (void)run;
    16 @end
    17 @implementation Dog
    18 - (void)run
    19 {
    20     NSLog(@"Dog---跑");
    21 }
    22 - (void)eat
    23 {
    24     NSLog(@"Dog---吃");
    25 }
    26 @end
    27 
    28 //Cat类
    29 @interface Cat : Animal
    30 - (void)eat;
    31 @end
    32 @implementation Cat
    33 - (void)eat
    34 {
    35     NSLog(@"Cat---吃");
    36 }
    37 @end
    38 
    39 //定义一个函数  喂动物
    40 void feed(Animal *a)
    41 {
    42     [a eat];
    43 }
    44 int main(int argc, const char * argv[])
    45 {
    46     //函数参数为父类类型,父类和子类对象都可以传入
    47     Animal *aa = [Animal new];
    48     feed(aa);
    49 
    50 
    51     Dog *d = [Dog new];
    52     feed(d);
    53     Cat *c = [Cat new];
    54     feed(c);
    55     
    56     //父类对象不能直接调用子类方法,必须强转为子类类型才可以调用子类方法
    57     Animal *animal1 = [Dog new];
    58     //父类对象不能直接调用子类方法
    59     //[animal1 run]
    60     Dog *a1 = (Dog *)animal1;
    61     [a1 run];
    62     return 0;
    63 }

    局限性:

    1>父类类型的变量  不能直接调用子类特有的方法

    2>必须强转为子类类型变量后,才可以调用子类特有的方法

    人生之路,不忘初心,勿忘始终!
  • 相关阅读:
    POJ 3292 Semi-prime H-numbers (素数筛法变形)
    POJ 1845 Sumdiv (整数拆分+等比快速求和)
    POJ 2635 The Embarrassed Cryptographer(大数求余)
    POJ 2115 C Looooops (扩展欧几里德 + 线性同余方程)
    poj3071
    poj2486
    poj1947
    POJ 1159
    POJ 1845
    poj3282
  • 原文地址:https://www.cnblogs.com/xdl745464047/p/4000672.html
Copyright © 2011-2022 走看看