zoukankan      html  css  js  c++  java
  • Objective-c 子类重写方法调用[super method]小实验

    最近温习《learn objective-c on the mac》

    第4章关于重写的调用了[super setFillColor:c]很不理解其作用,可能是因为翻译逻辑不清的原因吧,特地写了个小例子理解一下

    定义一个father类和son类

    father:

    #import <Foundation/Foundation.h>
    
    @interface father : NSObject
    {
        int num;
    }
    -(void)setNum:(int)num;
    
    @end
    #import "father.h"
    
    @implementation father
    -(void)setNum:(int)c
    {
        num = c;
        NSLog(@"i am father");
    }
    @end

    son:

    #import <Foundation/Foundation.h>
    #import "father.h"
    @interface son : father
    
    -(void)setNum:(int)num;
    @end
    #import "son.h"
    
    @implementation son
    -(void)setNum:(int)c
    {
        num = c;
        if (1 == num) {
            NSLog(@"i am son");
        }
        [super setNum:c];//这里是关键
        
    }
    @end

    main:

    #import <Foundation/Foundation.h>
    #import "son.h"
    int main(int argc, const char * argv[])
    {
        @autoreleasepool {
            son *ii = [[son alloc]init];
            [ii setNum:1];
        }
        return 0;
    }

    输出结果:

    2014-08-06 11:00:35.731 testtest[13606:303] i am son
    2014-08-06 11:00:35.732 testtest[13606:303] i am father

    如果去掉[super setNum:c],就只输出i am son。很明显了,子类重写方法添加自己的特性,而通过[super method]来保留父类的特性。

  • 相关阅读:
    react 组件间通信,父子间通信
    微信公众号配置及微信jsAPI支付
    Vue 幸运大转盘
    Hystrix断路器配置属性解析
    使用熔断器仪表盘监控(hystrix)
    使用熔断器防止服务雪崩
    创建服务消费者(Feign)
    Spring Cloud Ribbon配置详解
    创建服务消费者(Ribbon)
    创建服务提供者
  • 原文地址:https://www.cnblogs.com/happyacm/p/3894102.html
Copyright © 2011-2022 走看看