我试图了解多态,我的理解是它意味着你可以在多个类中使用相同的方法,并且在运行时将根据它所调用的对象的类型调用正确的版本.
以下示例说明:
http://www.tutorialspoint.com/objective_c/objective_c_polymorphism.htm
"Objective-C多态性意味着对成员函数的调用将导致执行不同的函数,具体取决于调用该函数的对象的类型."
在示例中,square和rectangle都是shape的子类,它们都实现了自己的calculateArea方法,我假设它是用于演示多态概念的方法.他们在Square对象上调用'calculateArea'并调用squareArea方法,然后在Rectangle对象上调用'caculateArea'并调用rectangle的calculateArea方法.它不是那么简单,当然这很明显,square甚至不知道矩形'calculateArea'是一个完全不同的类,所以不可能混淆使用哪个版本的方法.
我错过了什么?
你是对的,那个例子没有说明多态性.这就是他们应该如何写出这个例子.
#import <Foundation/Foundation.h> //PARENT CLASS FOR ALL THE SHAPES @interface Shape : NSObject { CGFloat area; } - (void)printArea; - (void)calculateArea; @end @implementation Shape - (void)printArea{ NSLog(@"The area is %f", area); } - (void)calculateArea { NSLog(@"Subclass should implement this %s", __PRETTY_FUNCTION__); } @end @interface Square : Shape { CGFloat length; } - (id)initWithSide:(CGFloat)side; @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 *shape_s = [[Square alloc]initWithSide:10.0]; [shape_s calculateArea]; //shape_s of type Shape, but calling calculateArea will call the //method defined inside Square [shape_s printArea]; //printArea implemented inside Square class will be called Shape *shape_rect = [[Rectangle alloc] initWithLength:10.0 andBreadth:5.0]; [shape_rect calculateArea]; //Even though shape_rect is type Shape, Rectangle's //calculateArea will be called. [shape_rect printArea]; //printArea of Rectangle will be called. [pool drain]; return 0; }