pragma mark 構(gòu)造方法練習(xí)
pragma mark 概念
pragma mark 代碼
#import <Foundation/Foundation.h>
#pragma mark 類
#import "Person.h"
#import "Student.h"
#pragma mark main函數(shù)
int main(int argc, const char * argv[])
{
#warning 讓學(xué)生繼承人類,要求學(xué)生對象初始化之后,年齡是10, 學(xué)號是1, 怎么辦?
// Person *p = [[Person alloc]init];
// NSLog(@"P2 = %@",p);
// Person *p1 = [[Person alloc]init];
// NSLog(@"P1 = %@",p1);
Student *stu = [[Student alloc]init];
NSLog(@"%@",stu);
Student *stu1 = [[Student alloc]init];
NSLog(@"%@",stu1);
return 0;
}
Person.h //人類 (父類)
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
@end
Person.m
#import "Person.h"
@implementation Person
- (instancetype)init
{
if (self = [super init]) {
// 如果父類 不等于空
// 初始化 子類
_age = 10;
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"age = %i",_age];
}
@end
Student.h // 學(xué)生類 (子類)
#import "Person.h"
@interface Student : Person
@property int no; // 學(xué)號
@end
Student.m
#import "Student.h"
@implementation Student
- (instancetype)init
{
if (self = [super init]) {
// [self setAge:10];
_no = 10;
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"age = %i, no = %i",[self age],[self no]];
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。