//
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
@property NSString *name;
/*
自定义构造方法:
其实就是自定义一个init方法
1.一定是对象方法
2.一定返回id/instancetype
3.方法名称一定以init开头
*/
- (instancetype)initWithAge:(int)age;
//- (instancetype)initwithAge:(int)age; // 注意: 自定义构造方法中的init后面的With的W一定要大写
// 一个类可以有0个或者多个自定义构造方法
- (instancetype)initWithName:(NSString *)name;
// 自定义构造方法可以有1个或多个参数
- (instancetype)initWithAge:(int)age andName:(NSString *)name;
@end
//
// Person.m
#import "Person.h"
@implementation Person
- (instancetype)init
{
if (self = [super init]) {
_age = ;
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"age = %i, name = %@", _age, _name];
}
- (instancetype)initWithAge:(int)age
// 注意: 自定义构造方法中的init后面的With的W一定要大写
//- (instancetype)initwithAge:(int)age
{
if (self = [super init]) {
_age = age;
}
return self;
}
- (instancetype)initWithName:(NSString *)name
{
if (self =[super init]) {
_name = name;
}
return self;
}
- (instancetype)initWithAge:(int)age andName:(NSString *)name
{
if (self = [super init]) {
_age = age;
_name = name;
}
return self;
}
@end
//
// Student.h
#import "Person.h"
@interface Student : Person
@property int no; // 学号
- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no;
@end
//
// Student.m
// day14
#import "Student.h"
@implementation Student
- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no
{
/*
if (self = [super init]) {
// _age = age;
// 狗拿耗子, 多管闲事
// 自己的事情自己做
[self setAge:age];
[self setName:name];
}
*/
if (self = [super initWithAge:age andName:name]) {
_no = no;
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"age = %i, name = %@, no = %i", [self age], [self name], _no]; //父类的属性是私有的。
}
@end
//
// main.m
// 自定义构造方法在继承中的表现
#import <Foundation/Foundation.h>
#import "Student.h"
#import "Person.h"
int main(int argc, const char * argv[]) {
// Student *stu = [[Student alloc] initWithAge:30 andName:@"lnj"];
Student *stu = [[Student alloc] initWithAge: andName:@"lnj" andNo:];
NSLog(@"%@", stu);
return ;
}