Objective-C繼承



面向物件程式設計中最重要的概念之一就是繼承。繼承允許我們根據另一個類來定義一個類,這使得建立和維護應用程式更加容易。這也提供了程式碼功能重用和快速實現時間的機會。

建立類時,程式設計師可以指定新類應該繼承現有類的成員,而不是完全編寫新的資料成員和成員函式。這個現有類稱為基類,新類稱為派生類

繼承的概念實現了is a關係。例如,哺乳動物是動物,狗是哺乳動物,因此狗也是動物,依此類推。

基類和派生類

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(@"Name: %@", personName);
   NSLog(@"Age: %ld", personAge);
   NSLog(@"Education: %@", employeeEducation);
}

@end

int main(int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];        
   NSLog(@"Base class Person Object");
   Person *person = [[Person alloc]initWithName:@"Raj" andAge:5];
   [person print];
   NSLog(@"Inherited Class Employee Object");
   Employee *employee = [[Employee alloc]initWithName:@"Raj" 
   andAge:5 andEducation:@"MBA"];
   [employee print];        
   [pool drain];
   return 0;
}

編譯並執行上述程式碼後,將產生以下結果:

2013-09-22 21:20:09.842 Inheritance[349:303] Base class Person Object
2013-09-22 21:20:09.844 Inheritance[349:303] Name: Raj
2013-09-22 21:20:09.844 Inheritance[349:303] Age: 5
2013-09-22 21:20:09.845 Inheritance[349:303] Inherited Class Employee Object
2013-09-22 21:20:09.845 Inheritance[349:303] Name: Raj
2013-09-22 21:20:09.846 Inheritance[349:303] Age: 5
2013-09-22 21:20:09.846 Inheritance[349:303] Education: MBA

訪問控制和繼承

如果派生類在介面類中定義,則它可以訪問其基類的所有私有成員,但它不能訪問在實現檔案中定義的私有成員。

我們可以按照誰可以訪問它們來總結不同的訪問型別:

派生類繼承所有基類方法和變數,但以下情況例外:

  • 使用擴充套件在實現檔案中宣告的變數不可訪問。

  • 使用擴充套件在實現檔案中宣告的方法不可訪問。

  • 如果繼承的類實現了基類中的方法,則執行派生類中的方法。

廣告