- 不要等到明天,明天太遥远,今天就行动。
须读:看完该文章你能做什么?
在继承中,在父类的基础上,扩展的构造方法
学习前:你必须会什么?
什么是继承,什么是自定义构造方法
继承:只要 A类继承了B类, 那么 B类 就拥有了 A类的所有属性 和方法
自定义构造方法:其实就是自定义一个init方法
一、本章笔记
二、code
main.m
#pragma mark 12-自定义构造方法在继承中的表现
#pragma mark 概念
#pragma mark - 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#import "Student.h"
#pragma mark - main函数
int main(int argc, const char * argv[])
{
// Student *s = [[Student alloc]initWithAge:33 andName:@"lyh"];
Student *s = [[Student alloc]initWithAge:33 andName:@"lyh" andNo:1];
NSLog(@"%@",s);
return 0;
}
Person
>>>.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
@property NSString *name;
- (instancetype)initWithAge:(int)age;
- (instancetype)initWithName:(NSString *)name;
- (instancetype)initWithAge:(int)age andName:(NSString *)name;
@end
>>>.m
#import "Person.h"
@implementation Person
- (instancetype)init
{
if (self = [super init]) {
_age = 10;
}
return self;
}
- (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;
}
- (NSString *)description
{
return [NSString stringWithFormat:@" age = %i , name = %@",_age,_name];
}
@end
Student
>>>.h�
#import "Person.h"
@interface Student : Person
@property int no; // 学号
- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no;
@end
>>>.m
#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];
_no = no;
}
*/
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