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ě)