1. 程式人生 > >[Objective-C語言教程]多態(26)

[Objective-C語言教程]多態(26)

2.0 int 類型 interface init 相關 5.0 eas elf

多態性這個詞表示有許多形式。 通常,當存在類的層次結構並且通過繼承相關時,會發生多態性。

Objective-C多態表示對成員函數的調用將導致執行不同的函數,具體取決於調用該函數的對象的類型。

考慮下面一個例子,有一個基類Shape類,它為所有形狀提供基本接口。 SquareRectangle類派生自基Shape類。

下面使用printArea方法來展示OOP特征多態性。

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Shape : NSObject {
 4    CGFloat area;
 5
} 6 7 - (void)printArea; 8 - (void)calculateArea; 9 @end 10 11 @implementation Shape 12 - (void)printArea { 13 NSLog(@"The area is %f", area); 14 } 15 16 - (void)calculateArea { 17 18 } 19 20 @end 21 22 @interface Square : Shape { 23 CGFloat length; 24 } 25 26 - (id)initWithSide:(CGFloat)side;
27 - (void)calculateArea; 28 29 @end 30 31 @implementation Square 32 - (id)initWithSide:(CGFloat)side { 33 length = side; 34 return self; 35 } 36 37 - (void)calculateArea { 38 area = length * length; 39 } 40 41 - (void)printArea { 42 NSLog(@"The area of square is %f", area);
43 } 44 45 @end 46 47 @interface Rectangle : Shape { 48 CGFloat length; 49 CGFloat breadth; 50 } 51 52 - (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth; 53 @end 54 55 @implementation Rectangle 56 - (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth { 57 length = rLength; 58 breadth = rBreadth; 59 return self; 60 } 61 62 - (void)calculateArea { 63 area = length * breadth; 64 } 65 66 @end 67 68 int main(int argc, const char * argv[]) { 69 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 70 Shape *square = [[Square alloc]initWithSide:10.0]; 71 [square calculateArea]; 72 [square printArea]; 73 Shape *rect = [[Rectangle alloc] 74 initWithLength:10.0 andBreadth:5.0]; 75 [rect calculateArea]; 76 [rect printArea]; 77 [pool drain]; 78 return 0; 79 }

執行上面示例代碼,得到以下結果 -

1 2018-11-16 02:02:22.096 main[159689] The area of square is 100.000000
2 2018-11-16 02:02:22.098 main[159689] The area is 50.000000

在上面的示例中,calculateAreaprintArea方法的可用性,無論是基類中的方法還是執行派生類。

多態性基於兩個類的方法實現來處理基類和派生類之間的方法切換。

[Objective-C語言教程]多態(26)