OC-021.OC的构造方法-02代码的复用和提取

在继承类中,如果新增加了成员变量。需要重新写构造方法,这时候就需要代码的提取,使代码更加简洁。

#import <Foundation/Foundation.h>//------main<pre name="code" class="objc">#import <Foundation/Foundation.h>

@interface LSPerson : NSObject
@property int age;//年龄
@property NSString *name;//姓名
- (instancetype) initWithAge:(int)age;
- (instancetype) initWithAge:(int)age andName:(NSString *)name;
@end

 
#import <Foundation/Foundation.h>//------LSperson.h

@interface LSPerson : NSObject
@property int age;//年龄
@property NSString *name;//姓名
- (instancetype) initWithAge:(int)age;
- (instancetype) initWithAge:(int)age andName:(NSString *)name;
@end
#import "LSPerson.h"//------LSPerson.m

@implementation LSPerson
- (instancetype) initWithAge:(int)age{
    return [self initWithAge:age andName:nil];
}
- (instancetype) initWithAge:(int)age andName:(NSString *)name{
    
    self = [super init];//  调用父类的init方法,让父类完成初始化
    if(self){           //  判断父类是否初始化成功,如果父类初始化成功才可以初始化自己
        self.age = age; //  在这里完成自己的初始化
        self.name = name;
    }
    return self;        //  返回指向自己的指针

}
@end
#import "LSPerson.h"//------LSStudent.h

@interface LSStudent : LSPerson
@property double height;//新增身高
- (instancetype) initWithAge:(int)age andName:(NSString *)name andHeight:(double)height;
@end
#import "LSStudent.h"//------LSStudent.m

@implementation LSStudent
// 第一种写法太繁琐
//- (instancetype) initWithAge:(int)age andName:(NSString *)name andHeight:(double)height{
//    if (self = [super init]) {
//        self.age= age;
//        self.name = name;
//        self.height = height;
//    }
//    return  self;
//}
//第二种写法,直接引用父类的方法
- (instancetype) initWithAge:(int)age andName:(NSString *)name andHeight:(double)height{
    if(self = [super initWithAge:age andName:name]){
        self.height = height;
    }
    return self;
}
@end






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值