08 继承

08 继承

Tags: Objective-C


继承是面向对象的三大特征之一,下面我们举个例子,Person类继承于NSObject,Student类继承于Person,Person类有name、age、nation三个属性,而Student类在这基础上增加了score属性有四个属性;其中在Person类中通过@property生成的_name、_age成员变量是private的,而nation的成员变量_nation是指定为protected的,而在Student类中,具有成员变量_nation和_score,_nation是继承自Person的,_score是自己生成的private的。

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject {
    @protected
    NSString *_nation;
}

@property (nonatomic, copy) NSString *name;//姓名
@property (nonatomic, assign) int age;//年龄
@property (nonatomic, copy) NSString *nation;//籍贯

//自定义实例构造方法
- (id) initWithName:(NSString *) name andAge:(int) age;
//自定义类构造方法
+ (id) personWithName:(NSString *) name andAge:(int) age;

@end

Person.m

#import "Person.h"

@implementation Person

- (id) initWithName:(NSString *)name andAge:(int)age {
    if (self = [super init]) {
        self.name = name;
        self.age = age;
    }
    return self;
}

+ (id) personWithName:(NSString *)name andAge:(int)age {
    Person *p = [[Person alloc ]initWithName:name andAge:age];
    return p;
}

//重写description方法
- (NSString *) description {
    return [NSString stringWithFormat:@"name:%@,age:%i", self.name, self.age];
}

@end

Student.h

#import "Person.h"

@interface Student : Person

@property (nonatomic, assign) float score;//分数

//自定义实例构造方法
- (id) initWithName:(NSString *)name andAge:(int)age andScore:(float) score;
//自定义类构造方法
+ (id) studentWithName:(NSString *) name andAge:(int) age andScore:(float) score;

@end

Student.m

#import "Student.h"

@implementation Student

- (id) initWithName:(NSString *)name andAge:(int)age andScore:(float)score {
    if (self = [super initWithName:name andAge:age]) {
        self.score = score;
    }
    return self;
}

+ (id) studentWithName:(NSString *)name andAge:(int)age andScore:(float)score {
    Student *s = [[Student alloc] initWithName:name andAge:age andScore:score];
    return s;
}

//重写description方法,这里能通过self.访问所有父类属性和自己定义的属性,但是self->只能访问自己的成员变量以及父类继承过来的protected成员变量
- (NSString *) description {
    return [NSString stringWithFormat:@"name:%@,age:%i,score:%.2f,nation:%@", self.name, self.age, self.score, self->_nation];
}

@end

main.m

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Student.h"

int main(int argc, const char * argv[]) {
    Person *p = [Person personWithName:@"Kin" andAge:28];
    NSLog(@"p=%@", p);

    Student *s = [Student studentWithName:@"Kaoru" andAge:27 andScore:100];
    s.nation = @"beijing";
    NSLog(@"s=%@", s);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值