Objective-C 多态

  • 多态

    多态一词意味着具有多种形式。通常,当存在类的层次结构并且它们通过继承关联时,就会发生多态。Objective-C多态性意味着对成员函数的调用将导致执行不同的函数,具体取决于调用该函数的对象的类型。考虑这个例子,我们有一个Shape类,它为所有形状提供了基本的接口。Square和Rectg从基类Shape派生。我们有一个方法printArea,它将展示有关OOP特征多态性的信息。
    
    @interface derived-class: base-class
    
    考虑如下基类Person及其派生类Employee-
    
    #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 Rectg : Shape {
       CGFloat length;
       CGFloat breadth;
    }
    
    - (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
    @end
    
    @implementation Rectg
    - (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 *square = [[Square alloc]initWithSide:10.0];
       [square calculateArea];
       [square printArea];
       Shape *rect = [[Rectg alloc]
       initWithLength:10.0 andBreadth:5.0];
       [rect calculateArea];
       [rect printArea];        
       [pool drain];
       return 0;
    }
    
    编译并执行上述代码后,将产生以下结果-
    
    2020-08-20 10:33:46.990 helloWorld[13112:13720] The area of square is 100.000000
    2020-08-20 10:33:46.997 helloWorld[13112:13720] The area is 50.000000
    
    在上面的示例中,基于calculateArea和printArea方法的可用性,将执行基类中的方法或派生类。多态性基于两个类的方法实现来处理方法在基类和派生类之间的切换。