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

 豆豆bo69_550 发布于 2023-02-13 19:18

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

以下示例说明:

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

我错过了什么?

1 个回答
  • 你是对的,那个例子没有说明多态性.这就是他们应该如何写出这个例子.

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

    2023-02-13 19:20 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有