Objective-c-polymorphism

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

Objective-Cポリモーフィズム

「多態性」という言葉は、多くの形式を持つことを意味します。 通常、ポリモーフィズムは、クラスの階層があり、それらが継承によって関連付けられている場合に発生します。

Objective-Cポリモーフィズムとは、メンバー関数を呼び出すと、その関数を呼び出すオブジェクトのタイプに応じて異なる関数が実行されることを意味します。

例について考えてみましょう。すべての形状の基本的なインターフェースを提供するShapeクラスがあります。 SquareおよびRectangleは、基本クラスShapeから派生します。

OOP機能 polymorphism について示すメソッドprintAreaがあります。

#import <Foundation/Foundation.h>

@interface Shape : NSObject {
   CGFloat area;
}

- (void)printArea;
- (void)calculateArea;
@end

@implementation Shape
- (void)printArea {
   NSLog(@"The area is %f", area);
}

- (void)calculateArea {

}

@end

@interface Square : Shape {
   CGFloat length;
}

- (id)initWithSide:(CGFloat)side;
- (void)calculateArea;

@end

@implementation Square
- (id)initWithSide:(CGFloat)side {
   length = side;
   return self;
}

- (void)calculateArea {
   area = length *length;
}

- (void)printArea {
   NSLog(@"The area of square is %f", area);
}

@end

@interface Rectangle : Shape {
   CGFloat length;
   CGFloat breadth;
}

- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
@end

@implementation Rectangle
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth {
   length = rLength;
   breadth = rBreadth;
   return self;
}

- (void)calculateArea {
   area = length* breadth;
}

@end

int main(int argc, const char *argv[]) {
   NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
   Shape *square = [[Square alloc]initWithSide:10.0];
   [square calculateArea];
   [square printArea];
   Shape *rect = [[Rectangle alloc]
   initWithLength:10.0 andBreadth:5.0];
   [rect calculateArea];
   [rect printArea];
   [pool drain];
   return 0;
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

2013-09-22 21:21:50.785 Polymorphism[358:303] The area of square is 100.000000
2013-09-22 21:21:50.786 Polymorphism[358:303] The area is 50.000000

メソッドcomputeAreaおよびprintAreaの可用性に基づく上記の例では、基本クラスまたは派生クラスのメソッドが実行されました。

多態性は、2つのクラスのメソッド実装に基づいて、基本クラスと派生クラス間のメソッドの切り替えを処理します。