继承

//
//  main.m
//  commandLineProject
//

#import 

// 定义接口
@interface Animal : NSObject
{
    // 添加一个成员变量
    NSString *name;
}

// 初始化自定义类的实例
- (id)initWithName:(NSString *)name;
- (void)say;
@end

// 实现实例方法
@implementation Animal

- (id)initWithName:(NSString *)animalName
{
    name = animalName;
    return self;
}

- (void)say
{
    NSLog(@"I am %@", name);
}

@end

// 继承 Animal 类
@interface Tiger : Animal

{
    float weight;
}
- (id)initWithName:(NSString *)animalName andWeight:(float)animalWeight;
- (void)hunt;

@end

// 实现继承类
@implementation Tiger

- (id)initWithName:(NSString *)animalName andWeight:(float)animalWeight
{
    name = animalName;
    weight = animalWeight;
    return self;
}

- (void)hunt
{
    NSLog(@"%@ whose weight is %.1f is hunting", name, weight);
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 初始化第一个实例,并赋值
        Animal *animal = [[Animal alloc] initWithName:@"Brain"];
        [animal say];
        
        Tiger *tiger = [[Tiger alloc] initWithName:@"Will" andWeight:99.2];
        [tiger say];
        [tiger hunt];
    }
    return 0;
}

你可能感兴趣的:(继承)