簡單說,就是利用 id 型態, id 是種特別的指標 (pointer) ,可以指向任何型態的物件。
舉例如下
#import <Foundation/Foundation.h>
@interface Animal: NSObject {
NSString *name;
}
@property (assign) NSString *name;
- (id) initAnimal;
- (void) sound;
@end
@implementation Animal
@synthesize name;
- (id) initAnimal
{
[super init];
name = @"someone";
return self;
}
- (void) sound
{
NSLog(@"hello");
}
@end
@interface Dog: Animal
@end
@implementation Dog
- (id) initAnimal
{
[super initAnimal];
name = @"dog";
return self;
}
- (void) sound
{
NSLog(@"bark");
}
@end
@interface Cat: Animal
@end
@implementation Cat
- (id) initAnimal
{
[super initAnimal];
name = @"cat";
return self;
}
- (void) sound
{
NSLog(@"meow");
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id a;
a = [[Animal alloc] initAnimal];
[a sound];
a = [[Dog alloc] initAnimal];
[a sound];
a = [[Cat alloc] initAnimal];
[a sound];
[pool drain];
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:classdemo18.m
功能:Objective-c 程式範例
作者:張凱慶
時間:西元 2013 年 4 月 */編譯執行,結果如下

| 中英文術語對照 | |
|---|---|
| 多型 | polymorphism |
| 變數 | variable |
| 動態型別 | dynamic typing |
| 動態聯繫 | dynamic binding |
| 指標 | pointer |
您可以繼續參考
類別
相關目錄
Objective-C 快速導覽
Objective-C 教材
首頁
參考資料
Programming with Objective-C: About Objective-C
Programming with Objective-C: Working with Objects
沒有留言:
張貼留言