#import "Person.h"
@implementation Person
- (id) initWithName:(NSString *)name withSex:(NSString *)sex withAge:(NSInteger)age
{
//第一步,调用父类的初始化方法,对父类的成员变量进行初始化
self = [super init];
//第二步,判断初始化是否成功(self不为空)
if (self) {
//对person类特有的成员变量一一赋值
_name = name;
_sex = sex;
_age = age;
}
//返回self
return self;
}
- (void) sayHi
{
NSLog(@"大家好,我是人类%@,性别:%@,今年%ld岁", _name, _sex, _age);
}
@end
</pre><pre name="code" class="objc">
<pre name="code" class="objc">#import "Student.h"
@implementation Student
- (id) initWithName:(NSString *)name withSex:(NSString *)sex withAge:(NSInteger)age school:(NSString *)school stuId:(NSInteger)stuId
{
//第一步,调用person的初始化方法
self = [super initWithName:name withSex:sex withAge:age];
//第二步,判断
if (self) {
//对student特有的成员变量一一赋值
_school = school;
_stuId = stuId;
}
//第三步,返回self
return self;
}
- (void) sayHi
{
[super sayHi];
NSLog(@"大家好,我是学生%@,性别:%@,今年%ld岁", _name, _sex, _age);
}
@end
另外:次要初始化方法中,一般要先调用self = 指派初始化方法,只需把指派初始化方法中不需要的参数设置为空,而次要初始化需要的参数设置为相应变量名即可.