Objective-C Polymorphism

The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

Objective-C polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

Consider the example, we have a class Shape that provides the basic interface for all the shapes. Square and Rectangle are derived from the base class Shape.

We have the method printArea that is going to show about the OOP feature polymorphism.

复制代码
 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Shape : NSObject
 4 
 5 {
 6     CGFloat area;
 7 }
 8 
 9 - (void)printArea;
10 - (void)calculateArea;
11 @end
12 
13 @implementation Shape
14 
15 - (void)printArea{
16     NSLog(@"The area is %f", area);
17 }
18 
19 - (void)calculateArea{
20 
21 }
22 
23 @end
24 
25 
26 @interface Square : Shape
27 {
28     CGFloat length;
29 }
30 
31 - (id)initWithSide:(CGFloat)side;
32 
33 - (void)calculateArea;
34 
35 @end
36 
37 @implementation Square
38 
39 - (id)initWithSide:(CGFloat)side{
40     length = side;
41     return self;
42 }
43 
44 - (void)calculateArea{
45     area = length * length;
46 }
47 
48 - (void)printArea{
49     NSLog(@"The area of square is %f", area);
50 }
51 
52 @end
53 
54 @interface Rectangle : Shape
55 {
56     CGFloat length;
57     CGFloat breadth;
58 }
59 
60 - (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
61 
62 
63 @end
64 
65 @implementation Rectangle
66 
67 - (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth{
68     length = rLength;
69     breadth = rBreadth;
70     return self;
71 }
72 
73 - (void)calculateArea{
74     area = length * breadth;
75 }
76 
77 @end
78 
79 
80 int main(int argc, const char * argv[])
81 {
82     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
83     Shape *square = [[Square alloc]initWithSide:10.0];
84     [square calculateArea];
85     [square printArea];
86     Shape *rect = [[Rectangle alloc]
87     initWithLength:10.0 andBreadth:5.0];
88     [rect calculateArea];
89     [rect printArea];        
90     [pool drain];
91     return 0;
92 }
复制代码

When the above code is compiled and executed, it produces the following result:

1 2013-09-22 21:21:50.785 Polymorphism[358:303] The area of square is 100.000000
2 2013-09-22 21:21:50.786 Polymorphism[358:303] The area is 50.000000

In the above example based on the availability of the method calculateArea and printArea, either the method in the base class or the derived class executed.

Polymorphism handles the switching of methods between the base class and derived class based on the method implementation of the two classes.

原文地址:https://www.cnblogs.com/xujinzhong/p/8430499.html