
- Objective-C 基礎
- Objective-C - 首頁
- Objective-C - 概述
- Objective-C - 環境設定
- Objective-C - 程式結構
- Objective-C - 基本語法
- Objective-C - 資料型別
- Objective-C - 變數
- Objective-C - 常量
- Objective-C - 運算子
- Objective-C - 迴圈
- Objective-C - 決策
- Objective-C - 函式
- Objective-C - 塊
- Objective-C - 數字
- Objective-C - 陣列
- Objective-C - 指標
- Objective-C - 字串
- Objective-C - 結構體
- Objective-C - 預處理器
- Objective-C - Typedef
- Objective-C - 型別轉換
- Objective-C - 日誌處理
- Objective-C - 錯誤處理
- 命令列引數
- 高階 Objective-C
- Objective-C - 類與物件
- Objective-C - 繼承
- Objective-C - 多型
- Objective-C - 資料封裝
- Objective-C - 分類
- Objective-C - 模擬
- Objective-C - 擴充套件
- Objective-C - 協議
- Objective-C - 動態繫結
- Objective-C - 複合物件
- Obj-C - Foundation 框架
- Objective-C - 快速列舉
- Obj-C - 記憶體管理
- Objective-C 有用資源
- Objective-C - 快速指南
- Objective-C - 有用資源
- Objective-C - 討論
Objective-C 多型
術語多型意指多種形式。通常,當存在類層次結構並且它們透過繼承相關聯時,就會發生多型。
Objective-C 多型意味著對成員函式的呼叫將導致執行不同的函式,具體取決於呼叫該函式的物件的型別。
例如,我們有一個類 Shape,它為所有形狀提供基本介面。Square 和 Rectangle 派生自基類 Shape。
我們有方法 printArea 將演示 OOP 特性多型。
#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
在上述示例中,根據方法 calculateArea 和 printArea 的可用性,基類或派生類中的方法將被執行。
多型根據兩個類的實現方法來處理基類和派生類之間的方法切換。
廣告