Objective-C 多态(Polymorphism)
多态性(polymorphism)一词意味着有多种形式。通常,当存在类的层次结构并且它们通过继承相关联时,就会发生多态。
Objective-C 多态性意味着对成员函数的调用将导致根据调用函数的对象类型执行不同的函数。
考虑这个例子,我们有一个类 Shape,它为所有形状提供了基本接口。Square 正方形和 Rectangle 矩形是从基类形状派生的。
我们有一个方法 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;}@endint 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;}
结果如下:
2022-07-07 21:21:50.785 Polymorphism[358:303] The area of square is 100.0000002022-07-07 21:21:50.786 Polymorphism[358:303] The area is 50.000000
在上面的实例中,基于方法 calculateArea 和 printArea 的可用性,执行基类或派生类中的方法。
多态性处理基于基类和派生类的方法实现的方法之间的切换。