这个多态性的例子是错的吗?

时间:2013-11-29 13:25:25

标签: ios objective-c polymorphism

我正试图了解多态,我的理解是它意味着你可以跨多个类使用相同的方法,并且在运行时将根据它被调用的对象的类型调用正确的版本。

以下示例说明:

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'是一个完全不同的类,所以不可能混淆使用哪个版本的方法。

我错过了什么?

2 个答案:

答案 0 :(得分:8)

你是对的,那个例子没有说明多态性。这就是他们应该写这个例子的方式。

#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;
}

答案 1 :(得分:0)

如教程点示例中所述,printArea(这解释了多态性)是基于基类或派生类中方法的可用性调用的。实际上calculateArea是特定于Rectangle和Square的独立方法,calculateArea没有解释多态性。它被你误解了。如果你创建一个Shape类型的对象,你也不能调用calculateArea方法,因为它没有方法calculateArea。

在这篇文章中找出正确答案,解释多态性。 What is the main difference between Inheritance and Polymorphism?

相关问题