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]来保留父类的特性。

你可能感兴趣的:(Objective-C)