Objective-C基礎(chǔ)學(xué)習(xí)之繼承中的自定義構(gòu)造方法

1.繼承中的自定義構(gòu)造方法

  • 不能在子類訪問(wèn)父類私有變量
@interface Person : NSObject

@property int age;

- (id)initWithAge:(int)age;
@end



@interface Student : Person

@property NSString *name;

- (id)initWithAge:(int)age andName:(NSString *)name;
@end

@implementation Student

- (id)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super init]) {
//        這個(gè)_Age是父類中通過(guò)property自動(dòng)在.m中生成的無(wú)法繼承,不能直接訪問(wèn)
//        _age = age;
        [self setAge:age];
        _name = name;
    }
    return self;
}
@end
  • 父類的屬性交給父類的方法來(lái)處理
@interface Person : NSObject

@property int age;

- (id)initWithAge:(int)age;
@end



@interface Student : Person

@property NSString *name;

- (id)initWithAge:(int)age andName:(NSString *)name;
@end

@implementation Student

- (id)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super initWithAge:age]) {
        _name = name;
    }
    return self;
}
@end
initsuper.png

2.自定義構(gòu)造方法的使用注意

  • (1)自己做自己的事情
  • (2)父類的屬性交給父類的方法來(lái)處理,子類的方法處理子類自己獨(dú)有的屬性
  • 自定義構(gòu)造方法必須以intiWith開(kāi)頭,并且’W’必須大寫(xiě)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容