八天学会OC

第04天OC语言(09):构造方法练习

2017-07-21  本文已影响8人  liyuhong
须读:看完该文章你能做什么?

快速熟悉构造方法

学习前:你必须会什么?

什么是构造方法
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

上一篇 下一篇

猜你喜欢

热点阅读