09-super关键

 

super关键字的作用

  1、直接调用父类中的某个方法

   2、super具体调用类方法还是对象方法,主要看super所处的环境:

    super处在对象方法中,那么就会调用父类的对象方法

      super处在类方法中,那么就会调用父类的类方法

   3、使用场合:子类重写父类的方法时想保留父类的一些行为

 1 // 僵尸
 2 @interface Zoombie : NSObject
 3 - (void)walk;
 4 
 5 + (void)test;
 6 - (void)test;
 7 
 8 @end
 9 
10 @implementation Zoombie
11 - (void)walk
12 {
13     NSLog(@"往前挪两步******");
14 }
15 
16 + (void)test
17 {
18     NSLog(@"Zoombie+test");
19 }
20 
21 - (void)test
22 {
23     NSLog(@"Zoombie-test");
24 }
25 @end
26 
27 // 跳跃僵尸
28 @interface JumpZoombie : Zoombie
29 + (void)haha;
30 - (void)haha2;
31 @end
32 
33 
34 @implementation JumpZoombie
35 
36 + (void)haha
37 {
38     [super test];
39 }
40 
41 - (void)haha2
42 {
43     [super test];
44 }
45 
46 - (void)walk
47 {
48     // 跳两下
49     NSLog(@"跳两下");
50     
51     // 走两下(直接调用父类的walk方法)
52     [super walk];
53     //NSLog(@"往前挪两步----");
54     
55 }
56 @end
57 
58 int main()
59 {
60     //[JumpZoombie haha];
61     JumpZoombie *jz = [JumpZoombie new];
62     
63     [jz haha2];
64     
65     return 0;
66 }

分析代码:

(1)考虑到实际中跳跃僵尸会"走两步跳一下",我们对父类Zoombie的walk方法进行了重写

这时候,第49行表示"跳两下",然后要让跳跃僵尸"往前挪两步",我们需要调用父类的walk方法,这时候就要用到super关键字。

(2)在5 6行,父类声明了两个test方法,一个是类方法,一个对象方法。我们要测试super什么时候调用类方法,什么时候调用对象方法。

因此,在36-44行我们在子类JumpZoombie中声明了两个方法,分别是类方法和对象方法

 

然后分别调用: [JumpZoombie haha]; 类名JumpZoombie调用类方法haha,优先去本类寻找,找到36-39行,执行,[super test]

输出结果为:Zoombie+test  说明此时super调用的是类方法

 

        [jz haha2]; 对象jz调用对象方法haha2,优先去本来寻找,找到41-44行,执行,[super test] 

输出结果:Zoombie - test  说明此时super调用的是对象方法。

 

 

       super处在对象方法中,那么就会调用父类的对象方法

      super处在类方法中,那么就会调用父类的类方法

 

posted @ 2014-09-29 13:00  微雨独行  阅读(187)  评论(0编辑  收藏  举报
1 2