为有牺牲多壮志,敢教日月换新天。

[Objective-C语言教程]多态(26)

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

多态性这个词表示有许多形式。 通常,当存在类的层次结构并且通过继承相关时,会发生多态性。

Objective-C多态表示对成员函数的调用将导致执行不同的函数,具体取决于调用该函数的对象的类型。

考虑下面一个例子,有一个基类Shape类,它为所有形状提供基本接口。 SquareRectangle类派生自基Shape类。

下面使用printArea方法来展示OOP特征多态性。

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

执行上面示例代码,得到以下结果 -

1 2018-11-16 02:02:22.096 main[159689] The area of square is 100.000000
2 2018-11-16 02:02:22.098 main[159689] The area is 50.000000

在上面的示例中,calculateAreaprintArea方法的可用性,无论是基类中的方法还是执行派生类。

多态性基于两个类的方法实现来处理基类和派生类之间的方法切换。

posted @ 2019-03-21 15:07  为敢技术  阅读(136)  评论(0编辑  收藏  举报