- 不要等到明天,明天太遥远,今天就行动。
须读:看完该文章你能做什么?
快速熟悉构造方法
学习前:你必须会什么?
什么是构造方法
init方法就是构造方法
一、本章笔记
二、code
main.m
#pragma mark 09-构造方法练习
#pragma mark 概念
#pragma mark - 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#import "Person.h"
#import "Student.h"
#pragma mark - main函数
int main(int argc, const char * argv[])
{
Person *p = [[Person alloc]init];
NSLog(@"%@",p);
Student *s = [[Student alloc]init];
NSLog(@"%@",s);
return 0;
}
Person
>>>.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
@end
>>>.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
#import "Person.h"
@interface Student : Person
@property int no;
@end
>>>.m
#import "Student.h"
@implementation Student
- (instancetype)init
{
if(self = [super init])
{
// [self setAge:10];
_no = 1;
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"age = %i, no = %i",[self age],_no];
}
@end
网友评论