iOS基础学习

Objective-C基础学习之继承中的自定义构造方法

2017-09-23  本文已影响4人  WenJim

1.继承中的自定义构造方法

@interface Person : NSObject

@property int age;

- (id)initWithAge:(int)age;
@end



@interface Student : Person

@property NSString *name;

- (id)initWithAge:(int)age andName:(NSString *)name;
@end

@implementation Student

- (id)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super init]) {
//        这个_Age是父类中通过property自动在.m中生成的无法继承,不能直接访问
//        _age = age;
        [self setAge:age];
        _name = name;
    }
    return self;
}
@end
@interface Person : NSObject

@property int age;

- (id)initWithAge:(int)age;
@end



@interface Student : Person

@property NSString *name;

- (id)initWithAge:(int)age andName:(NSString *)name;
@end

@implementation Student

- (id)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super initWithAge:age]) {
        _name = name;
    }
    return self;
}
@end
initsuper.png

2.自定义构造方法的使用注意

上一篇 下一篇

猜你喜欢

热点阅读