多態(tài)是指具有多種形式。通常情況下,多態(tài)發(fā)生時,有一個類層次結(jié)構(gòu)和繼承關(guān)系。
Objective-C的多態(tài)是指一個成員函數(shù)調(diào)用會導(dǎo)致執(zhí)行不同的功能,根據(jù)調(diào)用函數(shù)的對象的類型。
考慮這個例子中,我們有一類形狀,提供了基本的接口,為所有的形狀。Square 和Rectangle 來自基類Shape。
以下方法printArea是要顯示 OOP 多態(tài)性特點(diǎn)。
#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; }
上面的代碼編譯和執(zhí)行時,它會產(chǎn)生以下結(jié)果:
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方法的基類上是可用,在上面的例子中,無論是在基類中的方法還是執(zhí)行派生類。請注意Objective-C中我們不能訪問父類printArea方法,在這種情況下,方法是在派生類中實(shí)現(xiàn)的。
多態(tài)性處理方法基類和派生類的方法的基礎(chǔ)上實(shí)施的兩個類之間的切換。