super,superClass,class

来源:互联网 发布:人工智能程序设计java 编辑:程序博客网 时间:2024/06/10 23:10

研究super,superClass,class:

1.首先定义两个类,SubPerson继承Person;

2.在Person中声明一个方法(没有实现):

@interface Person : NSObject- (void)test;@end

3.在SubPerson中实现test方法:

- (void)test{     NSLog(@"%@ %@ %@ %@",[self class],[self superclass],[super class],[super superclass]);}

问题是四个输出各是什么?

4.在viewController中:

//创建一个子类对象,调用test方法;

@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    SubPerson *subP = [[SubPerson alloc] init];    [subP test];}@end

这里请注意,在第3步中会输出什么呢?

NSLog(@"%@ %@ %@ %@",[self class],[self superclass],[super class],[super superclass]);
 1>首先分析一下self,谁调用test,则self就是谁,viewController中是SubPerson调用,所以self是SubPerson; 2>class是求其类型; 3>superclass是求其父类的类型; 4>super是什么意思呢?      --super不是一个指针,仅仅是一个编译指示器;      —super仅仅是让当前对象调用父类的方法,调用者还是当前对象self;

结论:第3步中的输出分别是:SubPerson,Person,SubPerson,Person;

问题升级:
如果现在在Person中实现test方法:

@implementation Person- (void)test{     NSLog(@"%@ %@ %@ %@",[self class],[self superclass],[super class],[super superclass]);}@end

而在SubPerson中的test方法修改为:

@implementation SubPerson- (void)test{    [super test];}@end

则输出Person的test方法中输出会是什么呢?

分析:方法中的self的意思是谁调用当前方法,self就是谁,又在Person中的test方法任然是SubPerson在调用,所以self还是SubPerson,类推,super还是SubPerson,即输出还是:SubPerson,Person,SubPerson,Person;

0 0