Objective-C 多態性

Objective-C的多態是指一個成員函數調用會導致執行不同的功能，根據調用函數的對象的類型。

#import <Foundation/Foundation.h> @interface Shape : NSObject { CGFloat area; } - (void)printArea; @end @implementation Shape - (void)printArea{ NSLog(@"The area is %f", area); } @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]; Square *square = [[Square alloc]initWithSide:10.0]; [square calculateArea]; [square printArea]; Rectangle *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

printArea方法的基類上是可用，在上面的例子中，無論是在基類中的方法還是執行派生類。請注意Objective-C中我們不能訪問父類printArea方法，在這種情況下，方法是在派生類中實現的。