- 不要等到明天整以,明天太遙遠(yuǎn),今天就行動(dòng)峻仇。
須讀:看完該文章你能做什么公黑?
在繼承中,在父類(lèi)的基礎(chǔ)上摄咆,擴(kuò)展的構(gòu)造方法
學(xué)習(xí)前:你必須會(huì)什么?
什么是繼承凡蚜,什么是自定義構(gòu)造方法
繼承:只要 A類(lèi)繼承了B類(lèi), 那么 B類(lèi) 就擁有了 A類(lèi)的所有屬性 和方法
自定義構(gòu)造方法:其實(shí)就是自定義一個(gè)init方法
一、本章筆記
二吭从、code
main.m
#pragma mark 12-自定義構(gòu)造方法在繼承中的表現(xiàn)
#pragma mark 概念
#pragma mark - 代碼
#import <Foundation/Foundation.h>
#pragma mark 類(lèi)
#import "Student.h"
#pragma mark - main函數(shù)
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; // 學(xué)號(hào)
- (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; // 父類(lèi)的屬性不能使用 _去訪(fǎng)問(wèn)
// 狗拿耗子 多管閑事
// 自己的事情自己做
[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