A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 曦正 中级黑马   /  2016-2-19 10:35  /  3711 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1黑马币
昨天上课老师讲到了OC中一个super的用法,说是可以调用父类中的同名方法;
说到这里,我有个问题
  1. @interface Person:NSObject{
  2.    
  3. }
  4. +(void)run;
  5. @end
  6. @implementation Person

  7. +(void)run{
  8.     NSLog(@"人跑了~~");
  9. }
  10. @end

  11. @interface Police : Person
  12. +(void)run;
  13. @end

  14. @implementation Police
  15. +(void)run{
  16.     NSLog(@"警察开摩托车跑了~~");
  17. }
  18. @end

  19. @interface PoliceMaster : Police
  20. +(void)run;
  21. @end

  22. @implementation Police
  23. +(void)run{
  24.     NSLog(@"警察局长开汽车跑了~~");
  25. }
  26. @end
复制代码
如果说Police类想要调用Person中的类方法,那用一个[super run],这个就可以调用到了
那如果一个PoliceMaster这个类,如果也想调用Person中的run方法,那么用super怎么调用??

8 个回复

倒序浏览
在PoliceMaster重写父类的的方法里面 调用即可   [super run]  
回复 使用道具 举报
久伴 发表于 2016-2-19 11:17
在PoliceMaster重写父类的的方法里面 调用即可   [super run]

可我如果要调用Person中的run方法呢??
回复 使用道具 举报
本帖最后由 久伴 于 2016-2-19 14:08 编辑
曦正 发表于 2016-2-19 11:29
可我如果要调用Person中的run方法呢??

@interface Person:NSObject{
   
}
+(void)run;
@end
@implementation Person

+(void)run{
    NSLog(@"人跑了~~");
}
@end

@interface Police : Person
+(void)run;
@end

@implementation Police
+(void)run{
[super run]
    NSLog(@"警察开摩托车跑了~~");
}
@end

@interface PoliceMaster : Police
+(void)run;
@end

@implementation PoliceMaster
+(void)run{
[super run]
    NSLog(@"警察局长开汽车跑了~~");
}
@end

点评

子类调用父类的,父类调用爷爷的  发表于 2016-2-19 11:40
回复 使用道具 举报
说好的5币呢{:2_40:}
回复 使用道具 举报
久伴 发表于 2016-2-19 11:39
@interface Person:NSObject{
   
}

怎么调?附个代码看看
回复 使用道具 举报
久伴 中级黑马 2016-2-19 14:08:55
7#
曦正 发表于 2016-2-19 13:32
怎么调?附个代码看看

代码在上面啊   我都改完了
回复 使用道具 举报
  1. #import <Foundation/Foundation.h>

  2. @interface Person:NSObject{
  3.    
  4. }
  5. -(void)run;
  6. @end
  7. @implementation Person

  8. -(void)run{
  9.     NSLog(@"人跑了~~");
  10. }
  11. @end

  12. @interface Police : Person
  13. -(void)run;
  14. @end

  15. @implementation Police
  16. -(void)run{
  17.     [super run];
  18.     NSLog(@"警察开摩托车跑了~~");
  19. }
  20. @end

  21. @interface PoliceMaster : Police
  22. -(void)run;
  23. @end

  24. @implementation PoliceMaster
  25. -(void)run{
  26.     //调用Person方法
  27.     Person *p = [[Person alloc]init];
  28.     [p run];
  29.     NSLog(@"警察局长开汽车跑了~~");
  30. }
  31. @end


  32. int main(int argc, const char * argv[]) {
  33.     @autoreleasepool {
  34.         //调用Person方法
  35.         Person *p = [Person new];
  36.         [p run];
  37.         printf("--------\n");
  38.         //调用Police方法,Police调用父类的方法并追加信息
  39.         p = [Police new];
  40.         [p run];
  41.         printf("--------\n");
  42.         //调用PoliceMaster方法
  43.         p = [PoliceMaster new];
  44.         [p run];
  45.         
  46.     }
  47.     return 0;
  48. }
复制代码


super只能访问父类,如果你要在PoliceMaster中访问Person的run方法,只能通过实例化的方式调用
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马