0%

Objective-C 类的继承

本例ClassB继承自ClassA例 ClassA源代码:

#import 

@interface ClassA : NSObject
{
    int i;
}
-(void)initI;
-(void)printI;
@end

@implementation ClassA
-(void)initI
{
    i=100;
}
-(void)printI
{
    NSLog(@"i的值为%d",i);
}
@end

ClassB源代码:

#import "ClassA.h"

@interface ClassB : ClassA
-(void)addI:(int)n;
//增加自己的方法
@end

@implementation ClassB
-(void)addI:(int)n
{
    i+=n;
}
-(void)printI
{
    //重载Class中的printI方法
     NSLog(@"ClassB中重载方法 i的值为%d",i);
}
@end

main中使用方法:

#import 
#import "ClassA.h"
#import "ClassB.h"
//导入头文件
Boolean isSu(int);

int main (int argc, const char * argv[])
{
    
    @autoreleasepool {
        ClassA *a=[ClassA new];
        [a initI];
        [a printI];
        ClassB *b=[ClassB new];
        [b initI];
        [b printI];
        //调用继承自ClassA的initI和自身重载的printI方法
        [b addI:50];
        //调用ClassB自身的方法,使i增加50
        [b printI];
    }
    return 0;
}

输出结果: 2012-02-06 15:04:55.527 hello[476:707] i的值为100 2012-02-06 15:04:55.529 hello[476:707] ClassB中重载方法 i的值为100 2012-02-06 15:04:55.530 hello[476:707] ClassB中重载方法 i的值为150