面向對象編程中最重要的概念之一是繼承。繼承允許根據一個類定義另一個類,這樣可以更容易地創建和維護一個應用程式。 這也提供了重用代碼功能和快速實現時間的機會。
在創建類時,程式員可以指定新類應該繼承現有類的成員,而不是編寫全新的數據成員和成員函數。 此現有類稱為基類,新類稱為派生類。
繼承的想法實現了這種關係。 例如,哺乳動物是一個種類的動物,狗是一種哺乳動物,因此狗是一個動物等等。
1. 基礎和派生類
Objective-C只允許多級繼承,即它只能有一個基類但允許多級繼承。 Objective-C中的所有類都派生自超類NSObject
。
語法如下 -
@interface derived-class: base-class
考慮一個基類Person
及其派生類Employee
的繼承關係實現如下 -
#import <Foundation/Foundation.h>
@interface Person : NSObject {
NSString *personName;
NSInteger personAge;
}
- (id)initWithName:(NSString *)name andAge:(NSInteger)age;
- (void)print;
@end
@implementation Person
- (id)initWithName:(NSString *)name andAge:(NSInteger)age {
personName = name;
personAge = age;
return self;
}
- (void)print {
NSLog(@"Name: %@", personName);
NSLog(@"Age: %ld", personAge);
}
@end
@interface Employee : Person {
NSString *employeeEducation;
}
- (id)initWithName:(NSString *)name andAge:(NSInteger)age
andEducation:(NSString *)education;
- (void)print;
@end
@implementation Employee
- (id)initWithName:(NSString *)name andAge:(NSInteger)age
andEducation: (NSString *)education {
personName = name;
personAge = age;
employeeEducation = education;
return self;
}
- (void)print {
NSLog(@"姓名: %@", personName);
NSLog(@"年齡: %ld", personAge);
NSLog(@"文化: %@", employeeEducation);
}
@end
int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"基類Person對象");
Person *person = [[Person alloc]initWithName:@"Maxsu" andAge:25];
[person print];
NSLog(@"繼承類Employee對象");
Employee *employee = [[Employee alloc]initWithName:@"Yii bai"
andAge:26 andEducation:@"MBA"];
[employee print];
[pool drain];
return 0;
}
執行上面示例代碼,得到以下結果:
2018-11-16 01:51:21.279 main[138079] 基類Person對象
2018-11-16 01:51:21.280 main[138079] Name: Maxsu
2018-11-16 01:51:21.281 main[138079] Age: 25
2018-11-16 01:51:21.281 main[138079] 繼承類Employee對象
2018-11-16 01:51:21.281 main[138079] 姓名: Yii bai
2018-11-16 01:51:21.281 main[138079] 年齡: 26
2018-11-16 01:51:21.281 main[138079] 文化: MBA
2. 訪問控制和繼承
如果派生類在介面類中定義,則它可以訪問其基類的所有私有成員,但它不能訪問在實現檔中定義的私有成員。
可以通過以下方式訪問它們來執行不同的訪問類型。派生類繼承所有基類方法和變數,但以下情況除外 -
- 無法訪問在擴展幫助下在實現檔中聲明的變數。
- 無法訪問在擴展幫助下在實現檔中聲明的方法。
- 如果繼承的類在基類中實現該方法,則執行繼承類中的方法。
上一篇:
Objective-C類和對象
下一篇:
Objective-C多態性