1. 程式人生 > >oc36--自定義構造方法在繼承中的表現

oc36--自定義構造方法在繼承中的表現

ati import string tag ring 大寫 ace col sta

//
//  Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;
@property NSString *name;

/*
 自定義構造方法:
 其實就是自定義一個init方法
 1.一定是對象方法
 2.一定返回id/instancetype
 3.方法名稱一定以init開頭
*/
- (instancetype)initWithAge:(int)age;

//- (instancetype)initwithAge:(int)age;   // 註意: 自定義構造方法中的init後面的With的W一定要大寫

// 一個類可以有0個或者多個自定義構造方法 - (instancetype)initWithName:(NSString *)name; // 自定義構造方法可以有1個或多個參數 - (instancetype)initWithAge:(int)age andName:(NSString *)name; @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, name = %@", _age, _name]; } - (instancetype)initWithAge:(int)age // 註意: 自定義構造方法中的init後面的With的W一定要大寫 //- (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; } @end
//
//  Student.h

#import "Person.h"

@interface Student : Person

@property int no; // 學號

- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no;
@end
//
//  Student.m
//  day14

#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];
    }
     */
    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
//
//  main.m
//  自定義構造方法在繼承中的表現

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Person.h"

int main(int argc, const char * argv[]) {

//    Student *stu = [[Student alloc] initWithAge:30 andName:@"lnj"];
    Student *stu = [[Student alloc] initWithAge:30 andName:@"lnj" andNo:888];
    NSLog(@"%@", stu);
    return 0;
}

oc36--自定義構造方法在繼承中的表現