Objective-c-inheritance

提供:Dev Guides
移動先:案内検索

Objective-Cの継承

オブジェクト指向プログラミングで最も重要な概念の1つは、継承の概念です。 継承を使用すると、別のクラスの観点からクラスを定義でき、アプリケーションの作成と保守が容易になります。 これにより、コード機能を再利用して実装時間を短縮することもできます。

クラスを作成するとき、プログラマは完全に新しいデータメンバーとメンバー関数を記述する代わりに、新しいクラスが既存のクラスのメンバーを継承するように指定できます。 この既存のクラスは base クラスと呼ばれ、新しいクラスは derived クラスと呼ばれます。

継承の概念は、 is a 関係を実装します。 たとえば、哺乳類IS-A動物、犬IS-A哺乳類、したがって犬IS-A動物などです。

基本クラスと派生クラス

Objective-Cでは、マルチレベルの継承のみが許可されます。つまり、ベースクラスは1つしか持てませんが、マルチレベルの継承は許可されます。 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

アクセス制御と継承

派生クラスは、インターフェイスクラスで定義されている場合、その基本クラスのすべてのプライベートメンバーにアクセスできますが、実装ファイルで定義されているプラ​​イベートメンバーにはアクセスできません。

私たちは、次の方法でそれらにアクセスできる人に応じてさまざまなアクセスタイプを要約することができます-

派生クラスは、次の例外を除き、すべての基本クラスのメソッドと変数を継承します-

  • 拡張機能を使用して実装ファイルで宣言された変数にはアクセスできません。
  • 拡張機能を使用して実装ファイルで宣言されたメソッドにはアクセスできません。
  • 継承されたクラスが基本クラスのメソッドを実装する場合、派生クラスのメソッドが実行されます。